上题回顾与解析
public class Point {
protected int x,y;
private String name;
Point(int x,int y){
this.x = x;
this.y = y;
//3.此处调用子类的makeName方法
//因为该方法被子类方法覆盖了
this.name = makeName();
}
protected String makeName(){
return "["+ x + "," + y +"]";
}
@Override
public String toString(){
return name;
}
}
class ColorPoint extends Point{
private String color;
ColorPoint(int x, int y, String color){
//2.调用父类的构造方法
super(x,y);
this.color = color;
}
@Override
protected String makeName(){
//4.在ColorPoint构造函数未执行完时,color未null
//所以返回[4,2]:null
return super.makeName() + ":" + color;
}
public static void main(String[] args){
//1.调用子类的构造方法
System.out.println(new ColorPoint(4, 2, "blue"));
}
}
看完题目有点迷糊?那看来你并没有掌握好类的初始化顺序 这种题目理清楚执行顺序就好办。执行顺序及解析为题上面程序中的1234
每日一题
下面程序输出什么?
public class Name {
private final String first, last;
public Name(String first, String last){
this.first = first;
this.last = last;
}
@Override
public boolean equals(Object o){
if(o instanceof Name){
return false;
}
Name n = (Name)o;
return n.first.equals(first) && n.last.equals(last);
}
public static void main(String[] args){
Set<Name> s = new HashSet<>();
s.add(new Name("Mickey", "Mouse"));
System.out.println(
s.contains(new Name("Mickey", "Mouse")));
}
}
坚持日更:30天