当前位置: 技术问答>java相关
《thinking in java》一个有关继承的程序不明白,请讲一讲,谢谢
来源: 互联网 发布时间:2015-03-16
本文导语: 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() { a...
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 void print() { System.out.println(s); }
public static void main(String[] args) {
Cleanser x = new Cleanser();
x.dilute(); x.apply(); x.scrub();
x.print();
}
}
public class Detergent extends Cleanser {
// Change a method:
public void scrub() {
append(" Detergent.scrub()");
super.scrub(); // Call base-class version
}
// 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();
x.print();
System.out.println("Testing base class:");
Cleanser.main(args);
}
}
输出结果
Cleanser dilute() apply() Detergent.scrub() scrub() foam()
Testing base class:
Cleanser dilute() apply() scrub()
我认为Cleaner的成员变量s为私有,Detergent 无法继承,所以Detergent.main()
中的x.print();的结果为null dilute() apply() Detergent.scrub() scrub() foam()
还请各位给讲一讲。多谢多谢
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 void print() { System.out.println(s); }
public static void main(String[] args) {
Cleanser x = new Cleanser();
x.dilute(); x.apply(); x.scrub();
x.print();
}
}
public class Detergent extends Cleanser {
// Change a method:
public void scrub() {
append(" Detergent.scrub()");
super.scrub(); // Call base-class version
}
// 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();
x.print();
System.out.println("Testing base class:");
Cleanser.main(args);
}
}
输出结果
Cleanser dilute() apply() Detergent.scrub() scrub() foam()
Testing base class:
Cleanser dilute() apply() scrub()
我认为Cleaner的成员变量s为私有,Detergent 无法继承,所以Detergent.main()
中的x.print();的结果为null dilute() apply() Detergent.scrub() scrub() foam()
还请各位给讲一讲。多谢多谢
|
private String s; 无法继承没错,而这个s是存在的。 detergent并没有直接访问s,
而是通过public的方法来访问s, 所以执行结果使没问题的
而是通过public的方法来访问s, 所以执行结果使没问题的
|
同意zych72(闹闹):
其实大家应该看看encapsulotion的定义:
hide some attribute of a class and provide some public interface to access them.
所以s虽然是private,但是访问方法是public,所以仍然可以访问阿
其实大家应该看看encapsulotion的定义:
hide some attribute of a class and provide some public interface to access them.
所以s虽然是private,但是访问方法是public,所以仍然可以访问阿