i'm currently learning inheritance and I'm having some trouble understanding the concept. For the following code could someone tell me why I can't declare a subclass of type Superclass?
public class Test{
public static void main(String[] args){
Superclass myA = new Superclass();
Superclass myB = new Subclass();
}
public class Superclass{
private string a;
public Superclass()
{
a="";
}
public void setA(String userA)
{
a = userA;
}
}
public class Subclass extends Superclass{
private String b;
public Subclass()
{
b = "";
}
public void setB(String userB)
{
b = userB;
}
public void display()
{
System.out.print(b)
}
}
myA doesnt give me any problems, but myB does. I want to be make an array of lets say Superclass, but I want to be able to use the Subclass.Something like this
Superclass[] X = new Superclass[2];
x[0] = new Subclass();
X[0].setB("hello");
X[0].display();
You are assigning subclass object to a superclass type variable(i.e,upcasting is done), its fine. But when u do that, only superclass methods can be accessed. So in order to access the subclass methods please do downcast to its subclass type. eg.
Superclass[] X = new Superclass[2];
X[0] = new Subclass();
((Subclass) X[0]).setB("hello");
((Subclass) X[0]).display();
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다