java解惑之值类

所谓的值类,就是其实例表示一个值的类。

查看下面的俩个 值类,其中一个表示平面上的点,另外一个表示有颜色的点。

<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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值