第四章 对象与类

final

public class Main {
    public static void main(String[] args) {
        People p = new People();
        p.test();
    }
}

class People{
    final int i = 0;
    final String s  = "hello ";
    final Car car = new Car("blue");
    public void test(){
        System.out.println("i = " + i + "Car color = " + car.getColor() + " hashcode: " + car.hashCode());
        // i = 1;
        // System.out.println("i = " + i + "Car color = " + car.getColor());
        car.setColor("red");
        System.out.println("i = " + i + "Car color = " + car.getColor() + " hashcode: " +  car.hashCode());
    }
}

class Car{
    private String color;
    public Car(String color){
        this.color = color;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
}
/**
输出结果:
i = 0 Car color = blue hashcode: 1239731077
i = 0 Car color = red hashcode: 1239731077

*/

 final修饰基本类型数据,数据为常量,不可修改值,修改会有如下提示。

final修饰对象,对象的引用不可变,对象的属性值可变。


static

public class Main {
    static int i = 0;
    int a = 0;
    public static void main(String[] args) {
        // System.out.println(a);  // a不能被引用,static 修饰的方法会早于常规变量被加载。
        System.out.println(i);
    }
}

static方法只能调用static修饰的成员变量。

static属性/代码块优先于构造函数被初始化:

public class Main {

    public static void main(String[] args) {
        Employee e = new Employee(3);
        Employee.test();
    }
}

class Employee{
    int a;
    {
        System.out.println("常规代码块");
    }

    static {
        System.out.println("static代码块");
    }

    public Employee(int i){
        System.out.println("构造方法调用");
        a = i;
    }

    static int b = 0;
    public static void test(){
        System.out.println("静态方法调用");
        b ++;
    }
}
/**
执行结果为:
static代码块
常规代码块
构造方法调用
静态方法调用
*/

构造器

每个类创建都会默认有一个无参构造,但是当我们实现了构造器以后,默认的无参构造会失效。

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值