第6章重复运用classes
一.继续(inheritance)
1.在derived class中overriding某个函数时,只能覆写base class中的接口,即base class中的public或protected或friendly函数。假如试图overriding一个private函数,虽然编译通过,但实际上你只是在derived class中添加了一个函数。如
class Cleanser{
private void prt(){//(b)
Java/lang/System.java.Html" target="_blank"System.out.println("Cleanser.prt()");
}
}
public class EXPlicitStatic extends Cleanser{
public void prt(){
java/lang/System.java.html" target="_blank"System.out.println("ExplicitStatic.prt()");
}
public static void main(java/lang/String.java.html" target="_blank"String[] args){
Cleanser x = new ExplicitStatic();
x.prt();//(a)
}
}
因为Cleanser中的prt()是private,所以不能在其derivedclass中被覆写。ExplicitStatic中的prt()只是ExplicitStatic中的一个函数,所以当试图在(a)处通过多态来调用prt()时,会发生错误。假如把(b)处的private去掉,则结果为
ExplicitStatic.prt()
2.Super的使用
1)通过要害字super可以调用当前class的superclass(父类)。
例6.1.1.1
class Base{
Base(){java/lang/System.java.html" target="_blank"System.out.println("Base()");}
public void scrub() { java/lang/System.java.html" target="_blank"System.out.println(" Base.scrub()"); }
}
class Cleanser extends Base{
private java/lang/String.java.html" target="_blank"String s = new java/lang/String.java.html" target="_blank"String("Cleanser");
public void append(java/lang/String.java.html" target="_blank"String a) { s+=a; }
public void dilute() { append(" dilute()"); }
public void apply() { append(" apply()"); }
public void scrub() { append(" scrub()"); }
public void print() { java/lang/System.java.html" target="_blank"System.out.println(s); }
Cleanser(){
java/lang/System.java.html" target="_blank"System.out.println("Cleanser(): " + s);
}
public static void testStatic(){
java/lang/System.java.html" target="_blank"System.out.println("testStatic()");
}
public static void main(java/lang/String.java.html" target="_blank"String[] args){
Cleanser x = new Cleanser();
x.dilute(); x.apply(); x.scrub(); x.print();
}
}
public class ExplicitStatic extends Cleanser{
ExplicitStatic(){
java/lang/System.java.html" target="_blank"System.out.println("ExplicitStatic()");
}
public void scrub(){
append(" Detergen.scrub()");
super.testStatic();
super.scrub();//调用的是Cleanser.scrub()
}
public void foam() { append(" foam()"); }
public static void main(java/lang/String.java.html" target="_blank"String[] args){
ExplicitStatic x = new ExplicitStatic();
x.dilute(); x.apply(); x.scrub(); x.foam();
x.print(); java/lang/System.java.html" target="_blank"System.out.println("Test base class:");
Cleanser.main(args);
testStatic();
}
}
运行结果:
Base()
Cleanser(): Cleanser
ExplicitStatic()
testStatic()
Cleanser dilute() apply() Detergen.scrub() scrub() foam()
Test base class:
Base()
Cleanser(): Cleanser
Cleanser dilute() apply() scrub()
testStatic()
2)通过super来调用superclass中的成员时,调用的是最近成员。