Java基础:对象

2019-11-20  本文已影响0人  远方的橄榄树

1、类与对象概念

2. 对象与引用

public class Person {
    public static void main(String[] args) {
        Person p = new Person();
    }
}

对于Person p = new Person();,很多人都会认为p是对象,这种理解其实是错误的。p是引用变量,它存储在栈中,new Person()会创建一个新的person对象存储在堆中,然后将存储地址传递给引用变量p

2、this关键字

public class Banana {
    
    private String name;
    
    private String color;
    
    public Banana() {}
    
    public Banana(String name) {
        this.name = name; // this.name表示这个对象的属性name
    }
    
    public Banana(String name, String color) {
        this(name); // 调用构造器
        this.color = color;
    }
    
    public static void f1() {
//        this.name;  // error
    }
}

3、 static关键字

public class Test {
    public static void main(String[] args) {
        System.out.println("水果1...");
        Fruit fruit1 = new Fruit();
        System.out.println("水果2...");
        Fruit fruit2 = new Fruit();
    }
}

class Apple {
    Apple() {
        System.out.println("苹果真好吃");
    }
}

class Fruit {
    static Apple apple = new Apple();
    
    static {
        System.out.println("静态代码块...");
    }
    Fruit() {
        System.out.println("Fruit init...");
    }
    public void f() {
//        static int i = 1; // error
    }
}
水果1...
苹果真好吃
静态代码块...
Fruit init...
水果2...
Fruit init...

由结果可知,静态初始化会先执行,而且只在第一次加载Fruit.class的时候执行,然后再调用构造器生成对象。
dui

访问权限

权限 类内 同包 不同包子类 不同包非子类
private × × ×
default × ×
protected ×
public
上一篇下一篇

猜你喜欢

热点阅读