172.16.0.151_20200825-陈政平

问题

public class Monkey {
private final String name ;
private final char gender ;

public Monkey( String name , char gender ) {
    super();
    this.name = name ;
    this.gender = gender ;
}

@Override
public String toString() {
    return "Monkey[name=" + name + ", gender=" + gender + "]";
}

public static void main(String[] args) {
    
    Monkey m = new Monkey( "孙悟空" , '男' ); // 此时Monkey实例是 【不可变对象】
    System.out.println( m );
    
    // m.name = "侯某" ; // The final field Monkey.name cannot be assigned
    // m.gender = '女' ;
    
}
}

1、为什么会调用 public String toString() 方法 ,具体的调用过程是怎么样的?

public class SmallMonkey extends Monkey {
private int age ;

public SmallMonkey( String name, char gender , int age ) {
    super(name, gender);
    this.age = age ;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

@Override
public String toString() {
    return "SmallMonkey[( " + super.toString() + " ) , age=" + age + "]";
}

public static void main(String[] args) {
    
    SmallMonkey m = new SmallMonkey( "孙小圣" , '男' , 50 ); // SmallMonkey实例不是 【不可变对象】
    System.out.println( m );
    
    m.setAge( 100 ); // 修改实例变量的值
    System.out.println( m );
    
}

}

private final char gender ;

private final String name ;

2,以上两句是用final修饰的为什么子类中还可以调用赋值?

还未解决

吐槽:

晚上教室里有点热

标签

© 2021 成都云创动力科技有限公司 蜀ICP备20006351号-1