JAva解惑の値クラス
値クラスとは、そのインスタンスが値を表すクラスです.
次の2つの値クラスを表示します.1つは平面上の点を表し、もう1つは色のある点を表します.
最終的に何を出力しますか?
[4,2]:null
上記の実行経路で理解できます
注意:
1、多態性
子クラスが親クラスのメソッドを書き換えた場合、子クラスでこの関数を呼び出すと、親インスタンスで呼び出されても子クラスメソッドが呼び出されます.
2、フィールド
インスタンスフィールドに値が割り当てられている場合、その値を取得する可能性があります.
ヒント:
コンストラクタは布団類の上書き方法を呼び出さないでください.
延長:
ColorPoint
[4,2]:null
次の2つの値クラスを表示します.1つは平面上の点を表し、もう1つは色のある点を表します.
<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