3 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html
父母和孩子有 2 個(gè)獨(dú)立的測(cè)試實(shí)例。正如你在這個(gè)例子中看到的。
public class Main {
public class Parent{
private String test = "parent test";
String getTest() {
return test;
}
}
public class Child extends Parent {
public String test = "child test"; // defining it here hides the parent field
@Override
String getTest() {
return test;
}
}
public static void main(String[] args) {
Main main = new Main();
Parent parent = main.new Parent();
System.out.println(parent.getTest());
Child child = main.new Child();
System.out.println(child.getTest());
}
}
輸出:
parent test
child test

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
它可能會(huì)違反信息隱藏
信息隱藏雖然是一種很好的做法,但與 Liskov 替換原則幾乎沒(méi)有關(guān)系。
(A) 子類應(yīng)始終提供至少與其父類(類)相同的行為。
這是真的,但通過(guò)禁止對(duì)繼承成員使用更嚴(yán)格的訪問(wèn)修飾符來(lái)實(shí)現(xiàn)。一個(gè)較弱的訪問(wèn)修飾符表面附加行為。
class A {
private int lastInput;
protected int getLastInput() {
return lastInput;
}
public int getSquareValue(int input) {
lastInput = input;
return getLastInput()*getLastInput();
}
}
class B extends A {
public int getLastInput() {
return super.getLastInput();
}
}
A aa = new A();
B bb = new B();
A ab = bb;
// All behaviors of A exist in B as well.
// B can be substituted for A.
System.out.println(aa.getSquareValue(5)); // 25
System.out.println(ab.getSquareValue(5)); // 25
// B also has new behaviors that A did not surface.
// This does not prevent B from substituting for A.
System.out.println(bb.getLastInput()); // 5
添加回答
舉報(bào)