我想知道在Java中是否有一种语言特性,使得超类的方法对于子类的成员不可见:
public class Subclass extends protected Superclass
或者其他。我给你举个例子。
这是你的超类。
public class A{
public String getA(){...}
public String getB(){...}
public String getC(){...}
public void setA(String a){...}
public void setB(String b){...}
public void setC(String c){...}
}
如果你想要继承A类,但又想保护其中的一些方法,而且除非你覆盖它们,否则你不能更改这些方法中的访问修饰符,那么你最终会得到类似于以下代码的结果-
public class B extends A{
private String getA(){return super.getA();}
private String getB(){return super.getB();}//These four methods have
private void setA(String a){super.setA(a);}//to be redeclared.
private void setB(String b){super.setB(b);}
public String getC(){return super.getC();}//These two methods can be
public void setC(String c){super.setC(c);}//removed.
public String getD(){...}
public void setD(String d){...}
}
要么你可以保留 A 的私有实例,并使用如下代码:
或者您可以保留 A 的私有实例,并使用以下代码:
public class B{
private A obj;
private String getA(){return obj.getA();}
private String getB(){return obj.getB();}//These four methods can also
private void setA(String a){obj.setA(a);}//be removed.
private void setB(String b){obj.setB(b);}
public String getC(){return obj.getC();}//These two methods are
public void setC(String c){obj.setC(c);}//redeclared.
public String getD(){...}
public void setD(String d){...}
}
你是否可以有一种方法,既能够接受两种方式,又不必重新声明任何方法?