i have 2 classes, called superclass and subclass, i tried to cast the subclass object to superclass, but its seems does not work when i want to use the subclass object from the superclass. Please help to explain. Thanks. These are the code:-
public class superclass
{
public void displaySuper()
}
System.out.println("Display Superclass");
}
}
public class subclass extends superclass
{
public void displaySub()
{
System.out.println("Display Subclass");
}
}
public class Testing
{
public static void main(String args[])
{
subclass sub = new subclass();
superclass sup = (superclass) sub;
when i tried to use the displaySub() from the subclass get error
sup.displaySub(); //the displaySub method cant found
}
}
Java can implicitly cast a subclass to a superclass. So you can use a subclass whenever a reference to its superclass is called for.
Assigning subclass object to a superclass variable Therefore, if you assign an object of the subclass to the reference variable of the superclass then the subclass object is converted into the type of superclass and this process is termed as widening (in terms of references).
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
Answer: Yes, you can pass that because subclass and superclass are related to each other by Inheritance which provides IS-A property.
A superclass cannot know subclasses methods.
Think about it this way:
You have a superclass Pet
You have two subclasses of Pet
, namely: Cat
, Dog
speak
Pet
superclass is aware of these, as all Pet
s can speak (even if it doesn't know the exact mechanics of this operation)Dog
however can do things that a cat cannot, i.e. eatHomework
Dog
to a Pet
, the observers of the application would not be aware that the Pet
is in fact a Dog
(even if we know this as the implementers)eatHomework
of a Pet
You could solve your problem by telling the program that you know sup
is of type subclass
public class Testing
{
public static void main(String args[])
{
subclass sub = new subclass();
superclass sup = (superclass) sub;
subclass theSub = (subclass) sup;
theSub.displaySub();
}
}
You could solve the problem altogether by doing something like this:
public class superclass
{
public void display()
}
System.out.println("Display Superclass");
}
}
public class subclass extends superclass
{
public void display()
{
System.out.println("Display Subclass");
}
}
public class Testing
{
public static void main(String args[])
{
subclass sub = new subclass();
superclass sup = (superclass) sub;
sup.display();
}
}
check out this tutorial on more info: overrides
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With