+ 1
Can any one explain me why this program output is 30
8 Answers
+ 2
So the behaviour here is called inheritance
The variables x and y are all in the parent class
Now initially instances (objects or replicas of the parent class and the child class was created)
Then values was set to the x and y of the Parent class
Now a new assignment was made for the x and y of the child class and since it actually inheriting from the parent class, it overrides the x and y of the parent
Hence calling the sum gives you 30 instead of 300
+ 2
touqeer ali
Parent class has properties x, y
child has single variable z but inheriting x, y are inherited from parent.
You are creating 2 objects
parent p = new parent();
child m = new child();
Each have it's own separate properties. Not shared(other than static). So p has x, y and m has x, y, z separate copies.
m.x = 10
m.y = 20 will set child class properties..
p.x = 100 , p.y = 200 will set parent class properties. All are separate copies in memory..
You are calling sum by object m, child class object. m.x is 10, m.y = 20
It's not assigning parent class values. You are assigning inherited variables from parent class, which are separate copies available to child.
That's what an object purpose.
Class is blue print. Object is real entity. You can any number of objects, each will have separate copied properties..
p.x refer to parent class variable
m.x refers to child class variable in your program.
Hope it helps...
+ 1
you are creating object of child
child m = new child();
and setting x,y which are declared in parent class
m.x=10;
m.y=20;
and you calling sum() of child class which return z+super.sum()
super.sum() returns x+y=> 10+20
z+30 => 0+30 => 30
z is still 0 default value, not assigned any so it prints 30 by
System.out.print(m.sum());
hope it helps..
+ 1
Jayakrishnaš®š³ how super.sum() returns 30 , plz explain
+ 1
super.sum() calls parent class sum() method which returns x+y and you set x as m.x=10 and y by m.y = 20 child class don't have x, y so it refers to parent class properties through Inheritance. so x+y is 30.. !!!!!
0
But i am assigning x=10 and y=20 to child class so why same values are assigning to parent class
0
You are using super keyword in your child class, super means supperclass which means that it refer to your parent class (your parent is your superclass and your subclass is the child class) its invoking or calling all the variables and also your methods inside the parents class that's why it returning 30 because x + y which you assign it as 10 + 20 right?
but here's the question what happen if you remove the super keyword? well it will loop forever why? you are calling the method itself in the child class. and it will be an error because it doesn't have a base