Thinking in Java 4th chap7笔记-复用类(五)
ta定义在别处,则肯定无法访问或者在定义一个测试类,测试类的main中调用private,肯定是无法访问的。
FinalData fd1 = new FinalData("fd1");
//fd1.valueOne++;//不能改变值
fd1.v2.i++;//引用是final的,不过对象不是常量
fd1.v1 = new Value(9);// 可以,因为该引用不是final的
for(int i = 0;i < fd1.a.length;i++)
{
fd1.a[i]++;//ok,因为数组里面的对象不是常量
}
//he final field X cannot be assigned
//fd1.v2 = new Value(0);//final引用,不能改变引用
//fd1.VALUE_3 = new Value(0);//原因同上
//fd1.a = new int[3];//原因同上
//注意:static final装载时已初始化,而不是每次创建新对象时都初始化
System.out.println(fd1);
System.out.println("Creating new FinalData");
FinalData fd2 = new FinalData("fd2");
System.out.println(fd1);
System.out.println(fd2);
System.out.println(fd1);
System.out.println(fd2);
}
}
/** 测试的一个引用对象 */
class Value
{
int i;
public Value(int i)
{
this.i = i;
}
}
package com.book.chap7.reuse;
import static java.lang.System.out;
/**
*
*测试子类继承中的重载名字屏蔽问题
*
子类重载方法不会屏蔽其在基类中的任何版本,这和C++不同
*
*@author landon
*@since JDK1.6
*@version 1.0 2012-4-17
*
*/
public class Hide
{
public static void main(Stringargs)
{
Bart bart = new Bart();
//在这里我们看到,Bart导出类没有屏蔽基类的任何doh版本
bart.doh('c');
bart.doh(2.0f);
bart.doh(new Milhouse());
}
}
/**
*
* 基类,含有两个重载方法,doh
*
* @author landon
*
*/
class Homer
{
char doh(char c)
{
out.println("doh(char)");
return 'l';
}
float doh(float f)
{
out.println("doh(float)");
return 1.0f;
}
}
class Milhouse
{
}
/**
*
* 一个导出类,继承自Home,并重载了基类的doh方法
*
* @author landon
*
*/
class Bart extends Homer
{
//Bart引入了一个新的重载方法,在C++中,如果派生类的函数与基类的函数同名(但是参数不同),则会屏蔽其同名的基类函数
void doh(Milhouse m)
{
out.println("doh(Milhouse)");
}
}
package com.book.chap7.reuse;
/**
*
*测试protected关键字
*
尽量不要提供protected域,而只提供protected方法
*
*@author landon
*@since JDK1.6
*@version 1.0 2012-4-18
*
*/
public class Orc extends Villain
{
private int orcNumber;
public Orc(String name,int number)
{
super(name);
this.orcNumber = number;
}
public void change(String name,int number)
{
//注:这里调用了基类的protected方法
//TODO 这里也可以调用super.setName()方法,因为setName为protected,该方法在子类可见
setName(name);
// super.setName(name);
orcNumber = number;
}
//这里调用了基类的toString方法
@Override
public String toString()
{
return "Orc " + orcNumber + ": " + super.toString();
}
public static void main(Stringargs)
{
Orc orc = new Orc("tracy", 20);
System.out.println(orc);
orc.change("landon", 5);
System.out.println(orc);
}
}
class Villain
{
private String name;
//protected方法
protected void setName(String nm)
{
name = nm;
}
public Villain(String name)
{
this.name = name;
}
@Override