Overridden method call in parent method - java

Considering the following:
public class Child extends Parent{
public boolean isMeh(){
return true;
}
public void childMethod() {
System.out.println("child: "+isMeh());
}
public static void main(String... args){
Child child = new Child();
child.parentMethod();
child.childMethod();
}
}
class Parent{
public boolean isMeh(){
return false;
}
public void parentMethod() {
System.out.println("parent: "+isMeh());
}
}
Output:
parent: true
child: true
It is pretty obvious when isMeh() is called within Child class, it calls the overridden method.
But when the overriden method is called within a method of the parent object, it still calls the child object's method.
I see that we create one child object and parentMethod is just inherited so when we call isMeh() it calls the available(overridden) one.
What would be the reason for this implementation in java?

Any class in an inheritance hierarchy of Parent, be it a Child, a Parent, or some Grandchild deriving from them, has exactly one implementation of the method called isMeh. When Child overrides isMeh of Parent with its own implementation, it replaces the implementation; as far as the Child is concerned, the implementation in the Parent no longer applies*.
When you instantiate Child and call its parentMethod, the method has access to only one method isMeh - that is, the implementation provided by the Child. That is why you get the behavior that you describe.
This behavior allows for very nice patterns: for example, you can write a "partial implementation" of a method in the parent by relying on "plug-in" functionality in the child class provided through overrides. This technique is known as Template Method Design Pattern.
* although Child retains an ability to call Parent's isMeh explicitly.

Related

Why "THIS" keyword denotes Child object into Parent class's method?

I'm using Child and Parent relationship using Inheritance. I had written a code where I use 'THIS' keyword in a method of Parent class and the same method is overridden in my Child class. When I call Parent class method from Child class overridden method using 'Super' keyword then in Parent class method, the 'THIS' keyword denotes Child object class, and when I call a method from Parent class method using 'THIS' keyword then It call Child class method(this method is same and also available in Parent & Child Class using overriding).
class Parent {
void onResume() {
println("Parent:OnResume" + this) // Here 'this' denotes Child class's Object
this.show() // here Child class's method is invoked
show() // here Child class's method is invoked as well
}
void show() {
println("Parent:Show")
}
}
class Child extends Parent {
override
void onResume() {
super.onResume()
println("Child:->OnResume" + this)
}
override
void show() {
println("Child:Show")
}
}
//Calling code
Parent parentRef = new Child()
parentRef.onResume()
If I create an Object of Child class using Parent class reference variable like
Parent parentRef = new Child()
then 'this' denotes Child object in onResume() method of Parent class and when we call show() method in Parent then it call Child class's show() method.
Please let me clear why it happens so. As I know 'this' refers Current object of the class so here why 'this' refers Child object from Parent class.
Please provide deep and internal details for this reason. Thanks in advance.
this references the current instance. If you create an instance of Child, the runtime type of this is Child, regardless of whether you write this in the parent class code or the child class code.
And if you call this.someMethod() in the Parent class code, if someMethod is overridden by Child class, the Child class method will be executed.
When you override a method, you overwrite the functionality of the overridden method.... unless the child class calls super.show() from somewhere. In other words, the child is in full control of whether the original (overridden) functionality is still available or not and from where it is available. (The child is not limited to calling super.show() from within the overridden show() but may call it from other methods and constructors as well!)

Should I use static binding?

I am learning late binding and static binding. Now I am confused about these code.
Here is my analysis:
hello() is non-static method, so we should use the dynamic binding, that is Child.
But there is no hello() method in child class, so go to its super class. Find hello() and print the first line "Hello from parent call calssMethod".
Since the classMethod() is static, so we should use static binding of c, that is also Child. So the output is "classMethod in Child".
So the out put should be
Hello from parent call calssMethod
classMethod in Child
class Parent{
public static void classMethod() {
System.out.println("classMethod in Parent");
}
public void instanceMethod() {
System.out.println("InstanceMethod in Parent");
}
public void hello() {
System.out.println("Hello from parent call calssMethod");
classMethod();
}
}
class Child extends Parent{
public static void classMethod() {
System.out.println("classMethod in Child");
}
public void instanceMethod() {
System.out.println("InstanceMethod in Child");
}
}
public class AA {
public static void main(String[] args) {
Child c = new Child();
c.hello();
}
}
Now, here is the problem. The IDE shows that the output is:
Hello from parent call calssMethod
classMethod in Parent
What's the right analysis process?
What if I make hello() method static?
Class (static) methods aren't overridden as instance methods. When you call the method 'hello()', it will use the method of the parent. When you refer to the class method there, you're referring to the method defined in the class 'Parent'.
Besides that, you should declare your Child instance as 'Parent c = new Child()'. Because you aren't adding new methods to your subclass but rather changing the implementation, you don't lose access to the methods of the subclass. If you were to have to method that returns a Parent object but you return a Child object declared as you did, you'd get problems.
EDIT: To add to this, usually there are 2 reasons to use inheritance: specialisation and extension.
For specialisation, you use define your methods in your superclass and your subclasses differ in how they implement those methods. For example a superclass Animal with subclasses Cat and Dog. 'Animal' has a method makeSound(). You can imagine that both subclasses are going to have a different implementation.
For extension, you use a superclass as a base class containing everything that overlaps. Other than that, the subclasses might have very different implementations and uses. A lot of interfaces have this kind of use.
Whenever we call child class's object, firstly it always find parent class and execute it. As you have static classMethod in both classes so it always run parent's classMethod not child's. You can achieve required answer only by overriding it.
If you make hello() method static even then it will give you same output.

Private method of call from Child Object

class Parent {
public Parent() {
System.out.println("Parent Default..");
System.out.println("Object type : " + this.getClass().getName());
this.method();
}
private void method() {
System.out.println("private method");
}
}
class Child extends Parent {
public Child() {
System.out.println("Child Default..");
}
public static void main(String[] args) {
new Child();
}
}
When I run this code it prints the class name of "this" = Child
but the "this" object is able to call the private method of parent class why?
when you extend the class the private methods will not be inherited .but the object of the child class contains object of the parent class so when the superclass constructor is called .you are able to call the superclass private method inside the super class
First of all, when calling new Child(), since there is not a declared non-argument constructor in Child class, it will simple call super() which is invoking the Parent constructor.
Then, when executing this.getClass().getName(), here this stands for a Child instance, this is why you get "Child" as the result. Remember, Object#getClass() returns the most specific class the object belongs to. see more from here.
About why this.method() works. First, because Child extends Parent, the Child instance is also a Parent instance. The java scope modifier controls where the methods or fields can be accessed. Taking Parent#method() as the example, the private modifier indicates that this method can only be accessed (invoked) inside the Parent class. And this is exactly how you code does. it invokes the method inside the constructor of Parent class, which compiles the rule. See more about java access control from here
private has nothing to do with the actual class of the object. A private member can be accessed by any code within the same top-level class. (A top-level class is one that's not nested, which is unrelated to inheritance)
method is defined in Parent, and the call this.method() is also in Parent, so it's allowed.
A parent instance is not created here, you can confirm this using jvisualjvm in the /bin folder of your jdk installation, the child instance is not created either. Parent constructor is still invoked.
output:
Parent Default..
Object type : com.packagename.Child
private method
Child Default..
Parent constructor can be invoked by child class.
While in the constructor of parent, as Krishanthy Mohanachandran has noted above, a private method can be legally invoked.
It is abvious, you can call any private members within the class but not outside the class.
In this case it is legal. In this program first the constrctor of the Parent will be called and you can call private method within the class.

calling parent class method from child class object in java

I have a parent class which has a method, in the child class I override that parent class's method. In a third class I make an object of child and by using that object I want call the method of parent class. Is it possible to call that parent class method ? If yes, then how?
If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.
public class PolyTest{
public static void main(String args[]){
new Child().foo();
}
}
class Parent{
public void foo(){
System.out.println("I'm the parent.");
}
}
class Child extends Parent{
#Override
public void foo(){
//super.foo();
System.out.println("I'm the child.");
}
}
This would print:
I'm the child.
Uncomment the commented line and it would print:
I'm the parent.
I'm the child.
You should look for the concept of Polymorphism.
Use the keyword super within the overridden method in the child class to use the parent class method. You can only use the keyword within the overridden method though. The example below will help.
public class Parent {
public int add(int m, int n){
return m+n;
}
}
public class Child extends Parent{
public int add(int m,int n,int o){
return super.add(super.add(m, n),0);
}
}
public class SimpleInheritanceTest {
public static void main(String[] a){
Child child = new Child();
child.add(10, 11);
}
}
The add method in the Child class calls super.add to reuse the addition logic.
First of all, it is a bad design, if you need something like that, it is good idea to refactor, e.g. by renaming the method.
Java allows calling of overriden method using the "super" keyword, but only one level up in the hierarchy, I am not sure, maybe Scala and some other JVM languages support it for any level.
Say the hierarchy is C->B->A with A being the base class.
I think there's more to fixing this than renaming a method. That will work but is that a fix?
One way is to refactor all the functionality common to B and C into D, and let B and C inherit from D: (B,C)->D->A Now the method in B that was hiding A's implementation from C is specific to B and stays there. This allows C to invoke the method in A without any hokery.
NOTE calling parent method via super will only work on parent class,
If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();
interface Vehicle {
//Non abstract method
public default void printVehicleTypeName() { //default keyword can be used only in interface.
System.out.println("Vehicle");
}
}
class FordFigo extends FordImpl implements Vehicle, Ford {
#Override
public void printVehicleTypeName() {
System.out.println("Figo");
Vehicle.super.printVehicleTypeName();
}
}
Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.

How to override method to invoke superclass' superclass method? [duplicate]

This question already has answers here:
Closed 13 years ago.
Part of me thinks that this shouldn't be possible (even if it is), but I'll ask anyway.
Given the following class hierarchy (Grandparent and Parent are from a 3rd party and thus, not under my control), how would I override myMethod() in Child such that it bypasses the overridden implementation in Parent and invokes the one in Grandparent?
class Grandparent {
public void myMethod() {
// do stuff
}
}
class Parent extends Grandparent {
#Override public void myMethod() {
super.myMethod();
// do something else
}
}
class Child extends Parent {
#Override public void myMethod() {
// ??? I want to *only* do what Grandparent did here
}
}
Pretend that the Parent class provides a lot of other helpful behavior and is a crucial element of Child's hierarchy (in other words, I'm not looking for "make Child a subclass of Grandparent".
The idea behind inheritance is that each class defines their methods how they need, so you don't need to be inspecting any code.
It seems like you're subclassing here just to re-use code, and that's not the idea of subclassing.
Maybe you should have a helper member to do some of the tasks you need, instead of subclassing, and have both "Child" and "Parent" classes extend "Grandparent".
The main question you need to ask yourself is: "Is Child really a descendant of Parent, Grandparent or neiter?" In other words, for every instance of Child, can I say it's a Parent?
If the answer is no, then you're subclassing wrongly: inheritance is supposed to mean something, not just code re-use (i.e. Ford IS ALSO a Car, not just "Ford" uses "Car" methods).
Assuming that I couldn't touch the code in Parent or Grandparent and assuming that I'm not, as Seb suggested (and as Steve apparently agreed) simply misusing inheritance entirely:
I'd create a local instance of a Grandfather object (or a local class extending Grandfather, if it's abstract) and access its interpretation of myMethod() directly. Of course, depending on how much state information myMethod() is supposed to read and/or manipulate, the amount of work involved could be anything from "easy" to "excruciating".
It's an ugly solution, and, depending on how much state information is accessed, could be brittle as hell. But if Grandfather is reliably stable and/or myMethod() is fairly self-contained, it could work. The devil is in the details, as always.
I definitely agree with Seb that this is re-use, not inheritance. But, hey. Re-use is often a Good Thing.
Not possible.
I would create a final helper method in grandparent instead. And have this method (which is overridden) call that helper.
class Grandparent {
public final void myHelperMethod() {
// do stuff
}
public void myMethod() {
myHelperMethod();
}
}
class Parent extends Grandparent {
#Override public void myMethod() {
super.myMethod();
// do something else
}
}
class Child extends Parent {
#Override public void myMethod() {
// ??? I want to *only* do what Grandparent did here
myHelperMethod();
}
}
Do you have control of the Parent class?
If so, could you add a method (myNewMethod) to the Parent that calls myMethod on Grandparent, and call myNewMethod from Child?
(I'm not a Java person, so don't know if you can only call a method in a superclass from an override of that method in a subclass)
class Grandparent {
public void myMethod() {
myHelperMethod();
}
}
class Parent extends Grandparent {
#Override public void myMethod() {
super.myMethod();
// do something else
}
public final void myNewMethod() {
super.myMethod();
}
}
class Child extends Parent {
#Override public void myMethod() {
// ??? I want to *only* do what Grandparent did here
myNewMethod();
}
}

Categories