所谓的值类,就是其实例表示一个值的类。
查看下面的俩个 值类,其中一个表示平面上的点,另外一个表示有颜色的点。
<span style="font-size:18px;">import java.util.*;
public class ColorPoint extends Point{
private final String color;
public ColorPoint(int x,int y,String color){
super(x,y);//(2) Chain to Point constructor
this.color = color;//initialize blank final-Too late
}
public String makeName(){
return super.makeName() + ":" + color;//(4) execute before subclass constructor body
}
public static void main(String[] args){
System.out.println(new ColorPoint(4,2,"purple"));//(1) incoke subclass constructor
}
}
class Point{
private final int x,y;
private final String name;
public Point(int x,int y){
this.x = x;
this.y = y;
name = makeName();//(3)invoke subclass method
}
protected String makeName(){
return "["+x+","+y+"]";
}
public String toString(){
return name;
}
}</span>
最终输出什么?
[4,2]:null
通过上面标示的执行路线可以理解
要注意:
1、多态性
如果子类重写了父类中的方法,那么子类里调用到这个函数时,调用的是子类方法,即使是在父类实例里面调用。
2、字段
在一个实例字段被赋值时,存在着取其值的可能。
提示:
构造器不要调用被子类覆写的方法。
延伸:
<span style="font-size:18px;">import java.util.*;
public class ColorPoint extends Point{
private String color;
public ColorPoint(int x,int y,String color){
super(x,y);
this.color = color;
}
public String makeName(){
return super.makeName() + ":" + color;
}
public static void main(String[] args){
System.out.println(new ColorPoint(4,2,"purple"));
}
}
class Point{
private int x,y;
private String name;
public Point(int x,int y){
this.x = x;
this.y = y;
name = this.makeName();
if(this instanceof ColorPoint){
System.out.println("ColorPoint");
}else
System.out.println("Point");
}
protected String makeName(){
return "["+x+","+y+"]";
}
public String toString(){
return name;
}
}</span>
ColorPoint
[4,2]:null