This question already has answers here:
Why is an instance variable of the superclass not overridden by a subclass?
(7 answers)
Closed 5 years ago.
I am new to java and was reading about dynamic dispatching. I tried its program but the output that I got was unexpected. So in the following code I made two classes one Parent and another Child and in the Child class I made object of Child class and refer it by the variable of type Parent class. When I used the that variable to print the value of i(int type instance variable of both class) I got the value of parent class but it should print value of i that is in the child class. Can anybody please clear this up?
`
class Parent
{
int i=10;
}
class Child extends Parent
{
int i=20;
public static void main(String ar[])
{
Parent obj= new Child();
System.out.println(obj.i);
}
}
`
Variables can't be overriden in Java, take a look at this other question:
why instance variable of super class is not overridden in sub class method
Related
This question already has answers here:
Hiding Fields in Java Inheritance
(2 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I have a parent class A which has a primitive type property x
public class A {
String type = "A";
int x = 5 ;
void increment()
{
x++ ;
System.out.println(x);
}
}
I have a child class B which extends from class A, This child class also has propery x of String type
public class B extends A {
String type = "B" ;
String x = "Hello";
}
Now, both parent and child class has instance variable x with different type( int and String).
Parent class A has a method to increase value of X and now the method is available in the child class B ( Class B extends Class A, so all the methods in class A are accessible in class B)
Now I have a main method in a Runner class,
public class Runnable {
public static void main(String[] args)
{
//Creating object
B instanceOfB = new B() ;
//Invoke increment method
instanceOfB.increment();
}
}
While running the main method, I got an OUTPUT : 6
I am invoking increment method using reference variable instanceOfB
instanceOfB.increment();
instanceOfB is an instance of Class B.
By invoking this function, we are trying to increase the value stored in variable x, but x has reference to a String Object.
It should either throws compile time reception or run time exception because we are trying to increase a String object, It is not possible but I got output 6.
The behavior of instance variables and instance methods in a class hierarchy is different. If you wanted to access the value in the subclass from the superclass, you would need to wrap the subclass value with an instance method that is declared in the superclass but overridden in the subclass.
This question already has answers here:
Polymorphism in java: Why do we set parent reference to child object?
(8 answers)
Closed 5 years ago.
class Parent {
int m;
}
class child extends Parent {
public static void main(String args[]) {
Parent x = new Child();
}
}
What is the meaning when we say x is of type Parent? Why do we make use of
such referencing while we can use Child x = new Child()?
A List<Shape> can contain rectangles, circles, if those are subtypes of Shape.
That's an example for why it's good.
Java resolve the class of an object dynamically. It means that the actual type of an object is resolved over the indicated type.
So, in your example, if Child contains an overloaded method from Parent, this method will be called first before the one inheritted from Parent.
This question already has answers here:
Superclass reference not able to call subclass method in Java
(2 answers)
Closed 6 years ago.
Consider, for example, the following code
class Main {
public static void main(String[] args) {
Parent obj = new Child();
obj.firstMethod(); // Prints >> from child Class (polymorphism, great!)
obj.secondMethod(); // why this call fails?
// the obj variable reference a Child object
// which has secondMethod!
}
static class Parent {
Parent() {}
void firstMethod () {
System.out.println("from Parent Class");
}
}
static class Child extends Parent {
Child() {}
#Override
void firstMethod () {
System.out.println("from child Class");
}
void secondMethod () {
//
}
}
}
So obj variable is just a reference of type Parent, and the actual object the reference is pointing to is of type Child. I can't understand why such access fails!
Because the declared type Parent doesn't contain the method : void secondMethod ().
So, the compilation fails.
The polymorphism works only if both classes (Parent and Child) have a common method which comes from the parent class and that the child class overrides as in your firstMethod() example.
In your case, you call a method specific to the child class, so you should declare
Child obj = new Child() or do a cast to Child when you call secondMethod().
Don't forget that Polymorphism allows variables to have a dynamic behavior by using at runtime the implementation of the effective instance behind the variable. It is therefore meaningful only if the classes share a same operation.
The language spec answer: refer to JLS Sec 15.12. Emphasis added.
15.12.1. Compile-Time Step 1: Determine Class or Interface to Search
The first step in processing a method invocation at compile time is to figure out the name of the method to be invoked and which class or interface to search for definitions of methods of that name.
...
For the class or interface to search, there are six cases to consider, depending on the form that precedes the left parenthesis of the MethodInvocation:
...
If the form is ExpressionName . [TypeArguments] Identifier, then the class or interface to search is the declared type T of the variable denoted by ExpressionName if T is a class or interface type, or the upper bound of T if T is a type variable.
15.12.2. Compile-Time Step 2: Determine Method Signature
The second step searches the type determined in the previous step for member methods.
In obj.secondMethod();, ExpressionName is obj, which has declared type Parent. As such, the declared type T is Parent, not Child, so only methods in Parent are searched for. There's no method in Parent called secondMethod, so it's a compile-time error.
This question already has answers here:
Overriding member variables in Java ( Variable Hiding)
(13 answers)
Closed 6 years ago.
class A
{
protected int i=10;
}
class B extends A
{
protected int i=15;
}
public class Test extends B
{
public static void main(String a[])
{
A obj=new Test();
System.out.print("i="+obj.i);
}
}
It's output is i=10, but how?
How is the memory allocation for the object will take place.
A obj=new Test();
Means, you are accessing the members of Class A and executing the methods of Test(polymorphism).
I suggest you to read the official docs on inheritance and polymorphism to understand deep.
Polymorphism is linked to objects not references. Since you are using a reference of type A, you will get A.i if you have method getI() in A and override it in B, then call obj.getI(), then you will get B.i's value
In java, Variable Overriding is not there. We have the concept of method Overriding.
In your code
A obj=new Test();
You can able to access members of A. If you have overridden same method in both the classes (Parent and Child). And you are calling that method with obj. This time you will get output from Child class overridden method. this is the concept of Polymorphism.
Line 1: A a = new A();
the method existence will be checked in A class and the method will be called from A class also.
a.g();//A class method will be called
System.out.print("i="+a.i);//A class i will be accessed
Line 2: A b = new B();
the method existence will be checked in A class and the method will be called from B class.
b.g();//B class method will be called and it will also check that it is` available in A also or not if not then compile time error.
System.out.print("i="+b.i);//A class i will be accessed
This question already has answers here:
Java Inheritance - instance variables overriding
(3 answers)
Closed 10 years ago.
I am learning java. I have a doubt in inheritance. When a child class extends parent class and parent class has a method which refers to a instance variable declared in parent. But the child class dint override this method and has declared instance variable with same name as the parent. In this case instance variable from child will be referred or parent will be referred. Below is the code snippet
class Parent {
int a;
Parent() {
System.out.println("in Parent");
a = 10;
}
void method() {
System.out.println(a);
}
}
class Child extends Parent {
int a;
Child() {
System.out.println("in Child");
a = 11;
}
}
public class Test {
public static void main(String args[]) throws IOException {
Parent p1 = new Child();
p1.method();
}
}
The output I get is
in parent
in child
10
Can someone please make me understand why its referring parent class's instance variable a and not child class's a.
Another doubt is, I understood hiding the method, when there is a static method in parent and child class also has declared a static method with same signature. Here hiding means ? what method is getting hidden ? If its the parent method can you please explain me ?
Thanks in advance.
Java instance variables cannot be overridden in a subclass. Java inheritance doesn't work that way.
In your example, there is no method hiding (or overriding or overloading) going on.
There is hiding of instance variables though. In class child, the declaration of a hides the declaration of a in parent, and all references to a in the child class refer to the child.a not the parent.a.
To illustrate this more plainly, try running this:
public static void main(String args[]) throws IOException {
child c1 = new child();
parent p1 = c1;
System.out.println("p1.a is " + p1.a);
System.out.println("c1.a is " + c1.a);
System.out.println("p1 == c1 is " + (p1 == c1));
}
It should output:
p1.a is 10
c1.a is 11
p1 == c1 is true
This demonstrates that there is one object with two distinct fields called a ... and you can get hold of both of their values, if the access permits it.
Finally, you should learn to follow the standard Java identifier conventions. A class name should ALWAYS start with a capital letter.
Instance variables are not overriden in sub-class. If you define a variable in your class with the same name as in your super class it's called shadowing of variables inheritance and polymorphism doesn't apply for instance variables. if you define method() in parent and override it in Child class. the below would invoke the Child's method() due to run-time polymorphism printing 11
parent p1 = new child();
invokes Child constructor
with the super() call invoke's parent's constructor
Print's "in the parent" and initializes Parent's a to 10
print's in child and initializes Childs a to 11
p1.method();// this invokes Child's method() during run-time
As you are not overriding method() in child class, when the statement,
parent p1 = new child();
is executed, parent version of method() will be executed, and the only a value known to parent class is its own a. hence it will print a=10 (as it is on the stack at that time).
finally, you are just shadowing the variable a from parent class to child class.
When you do this
Parent P1=new Child();
what JVM do is
first Initialize Parent()
||
second Initialize Child()
So , first Parent constructor get called and then child's , but the output value will be 11 , because p1 is referring to child's object.
The issue is you created a child instance and stored it in a reference of the parent. Hence, when your access the object's property, JVM refers to the parent's variable value.
In case, it would have been a child class's reference variables, you would have received the child class' variable value.
The above is a feature of Java.
As you create the Instance of Parent. so in run time the compiler call the parent object ,
try the Below code.
public static void main(String args[]) throws IOException {
child c1 = new child();
c1.method();
}