Superclass reference not able to call subclass method in Java
Let's try to look at this line the same way that the compiler would:
animal.dogMethod();
First, it needs to work out what animal
means. That's nice and easy - it's a local variable in the current method, so it doesn't need to look far.
The compile-time type of that variable is Animal
. The compiler doesn't care what the value of the variable will be at execution time - it only uses the information about the declared type.
So, that's what it uses to try to look up what dogMethod()
means within the context of animal
, i.e. with type Animal
. First it looks in Animal
, then in java.lang.Object
(the implicit superclass of Animal
) - but neither of those classes contains a declaration of dogMethod
. At that point, the compiler has to give up with an error - it can't find the method. It doesn't matter that the method is available on the execution-time type of the object that the value that animal
refers to. It has to bind it at compile-time, using only the information available at compile time.
The only decision made at execution time is which implementation of a method is used - for example, if you called animal.toString()
and the Dog
class had an override, e.g.
@Override public String toString() {
return "I'm a dog";
}
then the compiler would find the toString()
method from java.lang.Object
, so it would know that the method call was valid - but the implementation in Dog
would be used because of the execution-time type of the object.
Java Inheritance: Calling a subclass method in a superclass
I'm very new to java and would like to know whether calling a subclass
method in a superclass is possible.
A superclass doesn't know anything about their subclasses, therefore, you cannot call a subclass instance method in a super class.
where is the proper place to set public static void main.
I wouldn't recommend putting the main
method in the Admin
class nor the User
class for many factors. Rather create a separate class to encapsulate the main
method.
Example:
public class Main{
public static void main(String []args) {
User user1 = new Admin("Bill", 18, 2);
System.out.println("Hello "+user1.getName());
user1.getLevel();
}
}
why cant we use a reference variable of super class to access methods of its subclass(methods not available in super class)?
The compiler just knows that myShape
is a reference variable of type Shape
, which contains only one method displayShape()
, so according to the compiler, it is not possible to call a method drawCircle()
which the Shape
class does not contain.
The compiler is not concerned with what object this variable will hold at runtime. You may extend another class from the Shape
class at some later point of time, and use the myShape
reference to hold that subclass object. The compiler is just concerned with what type myShape
is at compile-time.
If your Circle
class happened to override the displayShape()
method, like below :
public class Circle extends Shape {
public void displayShape() {
System.out.println("I am a Circle!");
}
public void drawCircle() {
// Implementation here
}
}
the only decision happening at runtime would be which displayShape()
method to call.
Calling a subclass method from superclass
When you declare a variable as having the type of the superclass, you can only access (public) methods and member variables of the superclass through that variable.
Pet cat = new Cat("Feline",12,"Orange");
cat.getName(); // this is OK
cat.getColor(); // this is not OK, getColor() is not in Pet
To access the methods in the concrete class (Cat
in this case), you need to either declare the variable as the derived class
Cat cat = new Cat("Feline",12,"Orange");
cat.getName(); // OK, getName() is part of Cat (and the superclass)
cat.getColor(); // OK, getColor() is part of Cat
Or cast it to a type you know/suspect is the concrete type
Pet cat = new Cat("Feline",12,"Orange");
((Cat)cat).getName(); // OK (same as above)
((Cat)cat).getColor(); // now we are looking at cat through the glass of Cat
You can even combine the two methods:
Pet pet = new Cat("Feline",12,"Orange");
Cat cat = (Cat)pet;
cat.getName(); // OK
cat.getColor(); // OK
Accessing subclass members through super class reference variables
When the textbook says that you can't access subclass-specific members with x2
, it meant that you can't access them at compile time.
To the compiler. x2
is of type X
(though it's really of type Y
at runtime), so when the compiler sees you trying to access stuff defined in Y
, it spots and says "that is not defined in X
. You can't do that!"
However, we all know that at runtime, x2
stores a reference to a Y
object. At runtime, you can indeed access members defined in Y
with x2
. You can prove this by using reflection.
At runtime, x2
is of type Y
, so obviously Y
's implementation will be called.
call subclass methods by superclass reference
you cannot do that, as subclass's methods are not in your super class. In this case, though String is a subclass of Object as length() is not declared in java.lang.Object class its no possible to call length on its instance.
equals() method however is overriden in string class, thus Strings's equals() will be invoked
Is it possible for a superclass object to refer a subclass member method which is not inherited?
A parent object reference is just constrained by the methods that it has in its class definition. If those methods are overridden by subclass, and at run time, if the actual object referred by the parent reference is of subclass type, then that overridden method is invoked. It doesn't matter if the overridden method invokes methods that are not originally present in the parent class or accesses the variables that are not present in the parent class.
This is what polymorphism is all about. It is by design meant to be this way as it makes program extension easier in case if we have different specific inheritance hierarchies where the parent class need not know the exact implementation of certain methods and can make things implemented by the subclasses as some sort of contract.
Related Topics
Gradle - Getting the Latest Release Version of a Dependency
How to Create a Process in Java
Differencebetween <Jsp:Include Page = ... > and <%@ Include File = ... >
How to Set Up Default Schema Name in JPA Configuration
Soap Request to Webservice with Java
Capturing Browser Logs with Selenium Webdriver Using Java
Jce Cannot Authenticate the Provider Bc in Java Swing Application
Java's Fork/Join VS Executorservice - When to Use Which
How to Pass Jvm Options from Bootrun
Find an Array Inside Another Larger Array
Is the in Relation in Cassandra Bad for Queries
What Is the Most Accurate Encoding Detector
Org.Postgresql.Util.Psqlexception: Fatal: Sorry, Too Many Clients Already
Java: Right Shift on Negative Number
How Does the Java Array Argument Declaration Syntax "..." Work