面向对象新体验

public class OOP {
    public static void main(String[] args) {
        // 引用传递 和 值传递  与 js复杂类型和基本类型一样因为地址的原因改不改变传递的本身值

        // 类与对象的关系: 模板和实例的关系
        Student student = new Student("小明");
        System.out.println(student.name);
        student.study();
        student.mouse();
    }
}
// 一个类撑死只有类变量和方法两种属性
class Student{
    String name;  // 没赋值是null
    public static int age = 18;
    public void study(){
        System.out.println(this.name + "在学习"); // 方法中的this指向类
    }
    // 构造函数,当构造函数没有被重写时,不用写,一旦有被重载了需要写出来,否则无法实例化空参数的情况(☆)
    // 1、和类名相同
    // 2、无返回值
    public Student() {
    }
    public Student(String name) {
        this.name = name;
    }

    // static 修饰的方法和Student这个类一起加载,所以这里面不能调用类里的非静态成员变量、非静态方法
    public static void book(){
        System.out.println( "我在看书,我" + age + "岁"); // 只能直接调用静态成员变量
    }
    public void  mouse(){
        this.book();
    }
    public void keyboards(){
        System.out.println("我是学生用的键盘");
    }
    // 非静态方法可以调用静态和非静态前面可省略this.(为了理解最好不要省略)
    // 静态方法调用都不能用this.(因为静态方法加载的时候类还没有加载构造好)
}
你的努力有资格到拼天赋的程度吗?
原文地址:https://www.cnblogs.com/wchjdnh/p/14401997.html