老规矩,先上代码!
- Java code
//: c06:Detergent.java// Inheritance syntax & properties.class Cleanser { private String s = new String("cleanser"); public void append(String a) { s += a; } public void dilute() { append(" dilute()"); } public void apply() { append(" apply()"); } public void scrub() { append(" scrub()"); } public String toString() { return s; } public static void main(String args[]) { Cleanser x = new Cleanser(); x.dilute(); x.apply(); x.scrub(); System.out.println(x); }}public class Detergent extends Cleanser { // Change a method: public void scrub() { append(" Detergent.scrub()"); super.scrub(); } // Add methods to the interface: public void foam() { append("foam()"); } //Test the new class: public static void main(String args[]) { Detergent x = new Detergent(); x.dilute(); x.apply(); x.scrub(); x.foam(); System.out.println(x); System.out.println("Testing base class:"); }}
结果是Cleanser dilute() apply() Detergent.scrub() scrub() foam()
为什么不是Cleanser dilute() apply() scrub() Cleanser dilute() apply() Detergent.scrub() scrub() foam()?
求解答
------解决方案--------------------
咋看也不会是你那个效果啊。。。
你的问题是为啥第三个是 Detergent.scrub() 而不是 scrub()
因为 scrub() 被子类重写了,所以当然是调用子类的函数,然后:
public void scrub() {
append(" Detergent.scrub()");
super.scrub(); // 这句话回去调用父类的 scrub() 函数
}
至于你后面那一大串,就完全不理解你是啥意思了?
main函数可没有自动执行这个概念,main函数是JVM启动时指定调用哪个类的就是哪个类的。
类被实例化的时候,跟main函数完全不会发生任何联系。
------解决方案--------------------
- Java code
class Cleanser { private String s = new String("cleanser"); public void append(String a) { s += a; } public void dilute() { append(" dilute()"); } public void apply() { append(" apply()"); } public void scrub() { append(" scrub()"); } public String toString() { return s; } public static void main(String args[]) { Cleanser x = new Cleanser();//String s = "cleanser"; x.dilute();// s = "cleanser" +" dilute()"; x.apply();//s = "cleanser" +" dilute()" + " apply()"; x.scrub();//s = "cleanser" +" dilute()" + " apply()" +" scrub()"; System.out.println(x);// cleanser dilute() apply() scrub() }}