Bai*_* Li 6 java oop inheritance class
我想知道Java中是否存在一种语言特性,其中超类的方法对于子类的成员是不可见的:
public class Subclass extends protected Superclass
Run Code Online (Sandbox Code Playgroud)
或者其他的东西.我举个例子.
这是你的超类.
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){...}
}
Run Code Online (Sandbox Code Playgroud)
如果你想在保护它的某些方法的同时继承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){...}
}
Run Code Online (Sandbox Code Playgroud)
或者你可以保留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){...}
}
Run Code Online (Sandbox Code Playgroud)
你能不能以任何方式重新获得任何方法?
Uri*_*Uri 10
与C++中的情况不同,Java中没有"非公共"继承.
继承创建子类型关系.B的任何实例也是A的实例,并且应该响应相同的消息.如果B的实例显然不响应A实例响应的所有消息,则无论如何继承都是不合适的.
您的最后一个解决方案(B不从A继承)是合适的解决方案:您不创建子类型关系,只使用一种类型(秘密地)实现另一种类型.