[英]Can I make a protected member public in Java? I want to access it from a subclass
[英]can you make a public member of the superclass a protected member in a subclass?
就像標題中所說的那樣,您可以讓超類的公共成員成為子類中的受保護成員嗎? 我今天的考試中有這個問題,對編程我還是很陌生。 你能解釋一下嗎?
public class Animal {
int lifeExpectancy;
private int weight;
protected gender;
String name;
public String type;
String genders;
public Animal(int le, int w, char g, String n){
lifeExpectancy = le;
gender = g;
weight = w;
name = n;
}
這是子類
public class Pet extends Animal{
private String home;
private Boolean biten;
String message;
public Pet(int le, int w, char g, String n, String h, Boolean b) {
super(le, w, g, n);
lifeExpectancy = le;
gender = g;
weight = w;
name = n;
home = h;
biten = b;
}
不能。假設您的A
擴展了B
,請記住,這意味着您始終可以將A
用作B
B b = new A();
因此,不允許A
刪除或限制B
所做的任何事情,它只能擴展它。
在Java中,成員是構造函數,字段或方法。
class X1 {
public int x;
public X1() {
}
public void x () {
}
}
public class X extends X1 {
protected int x;
protected X() {
}
protected void x () {
}
}
編譯器僅在上面發現一個錯誤
- Cannot reduce the visibility of the inherited method from X1
而且它不可能允許它。 至於構造函數和字段,我們不更改超類成員的可見性,我們只是聲明新成員
您可以只繼承屬性。 而已。
考慮一種情況,如果您使用子類代替超類,並且修改了該子類的訪問器,則會破壞OOP規則。
您不能降低繼承項的可訪問性。 並且只有實例方法被繼承。 因此,您可以在可訪問性較低的子類中重新定義實例或靜態屬性(而不是方法)。
對於靜態方法,盡管它們不是繼承的,您仍然不能放棄可訪問性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.