calling parent class method from child class object in java - 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.

Related

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.

How can we call methods overridden in a java anonymous class?

Consider the code below :
abstract class AbstractClass {
abstract m1();
}
public class Test {
public static void main(String [] args) {
AbstractClass obj = new AbstractClass() {
#Override void m1() {
System.out.print("Instance of abstract class !");
}
};
obj.m1();
}
}
Now here is what I did not understand about this code.
I read that anonymous class creates the class with unknown name which extends the class whose reference is provided (here it is abstract AbstractClass).
Also I remember that we cannot implement the method of child class if the the object is having reference of parent class.
see block of code below
Parent obj = new Child();
obj.methodOfParent();
obj.methodOfChild(); //this gives error
Now here is my point if Anonymous Class extends its Parent Class whose reference is provided, then how can we call overriden methods of Parent Class from Anonymous Class?
I guess you just miss one point. Let me show you example:
class Parent {
public void methodOfParent() {}
public void methodOfParentToBeOverriden() {}
}
class Child extends Parent {
#Override public void methodOfParentToBeOverriden() {}
public void methodOfChild() {}
}
Parent obj = new Child();
obj.methodOfParent(); //this is OK
obj.methodOfParentToBeOverriden(); // this is OK too
obj.methodOfChild(); //this gives error
((Child)obj).methodOfChild(); //this is OK too here.
Please note that when you call obj.methodOfParentToBeOverriden() it will be called implementation from Child class. Independence did you cast this object to Parent type or not.
There is a difference between calling an overridden method of parent and calling a method of child. If a method is declared in class T, you can call it on a variable statically typed as T, regardless of where the method is actually implemented.
In your example, if obj.methodOfParent() happens to be a method override from Child, the method in Child will run, even though obj's static type is Parent.
Same mechanism is in play with anonymous classes: the reason that you are allowed to call obj.m1() is that m1() has been declared in the parent class.

Calling child constructor interlaced in parent constructor in java

I have lots of children to a base class and plan for adding a lot more. I'm lazy. The child creator sets up some basic things that is needed for the super constructor and vice versa. A simple solution from my problem would be the following:
parent {
public parent(){/*some code*/}
public void finalSetup(){/*code that dependent on the fact that the child constructor has run*/}
}
child{
public child(){/*some code;*/ super.finalSetup();}
}
How ever, calling super.finalSetup() on every child is quite the hassle, and if I forget it on one it'll break. That's no good. My question is simple: is there any way to set this up form the parent. As far as my google skills go I haven't been able to find one. Hopefully you guys know something I don't.
Thanks
Consider the Factory pattern to create generic type that extends Parent.
public class Parent {
public Parent(){/*some code*/}
public void finalSetup(){/*code that dependent on the fact that the child constructor has run*/}
public static <T extends Parent> T makeChild(Class <T> klass) {
T child = null;
try {
child = klass.newInstance();
child.finalSetup();
}
catch (InstantiationException| IllegalAccessException ex) {
// somthing went wrong
}
return child;
}
}
and call
Child child = Parent.makeChild(Child.class);
It is useful when:
+ a class can't anticipate the class of objects it must create
+ a class wants its subclasses to specify the fields or objects it creates
+ classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate
This should be what you want, but as already mentioned, it can be not the best idea. You don't need to explicitly call the parent constructor in your subclass if you have a no-argument constructor in your superclass.
abstract class Parent {
Parent() {
/*some code*/
childInit();
finalSetup();
}
void finalSetup() {/*code that dependent on the fact that the child constructor has run*/}
abstract void childInit();
}
class Child extends Parent {
#Override
void childInit() {
/* the code you would put in child's constructor */
}
}
This should do it. The basic idea is to override the before and after methods in your children and in the parent constructor you simply run both and do some initialization in between. Of course this does not save you from forgetting to call the parent constructor.
abstract class Parent {
Parent(){
doBefore();
// some stuff
doAfter();
}
abstract void doBefore();
abstract void doAfter();
}
class Child extends Parent {
Child(){
super();
}
void doBefore(){
// do before stuff
}
void doAfter(){
// do after stuff
}
}
With abstract methods in your parent you can implement any permutation of before / after procedures.

Referring to parent class in Java

I want to know if it possible to use This() To reffer MotherClass, Calling My motherClass A and executing it from my Child Class B. witch one is correct ?
Class A { A(){ System.out.println("hello");}
Class B extends A { this() ; B(){System.out.println("World");}}
OR
class A {
Class B { this(); B(){System.out.println("World");} }
}
I want when to Call Class B it show Me (HelloWorld);
Sorry for my bad english.
Calling this() is meaningless unless you are calling it in a constructor and which means to call a constructor overload for this current class (if one exists). Please see this tutorial for the details on this. To call a super class's methods, again use the super keyword.
Incidentally, your code still doesn't compile. Please understand that you can't be careless when coding -- the compiler won't let you, and neither should you be when creating and posting code for questions here.
Create a file - parent.java
public class parent {
parent(){
System.out.println("Hello");
}
}
Create another file - child.java
public class child extends parent {
child(){
super();
System.out.println("World");
}
public static void main(String[] args) {
child c = new child();
}
}
==============================
Creating an instance of child class will first call the parent class constructor and then the child class constructor; resulting in the o/p you are looking for.

How to have child override values of parent class, but use parent's method

Apologies if this has been posted before, I keep only getting results for overriding the opposite way.
I want to be able to do 2 things:
Reference the parent variable from the child class, in assigning the value for the child variable.
Have the method in the adult class that references this variable use the child classes value. That way, I can have a lot of child classes, but not have the same repeating code for the method.
Here's a super simple pseudo-example of what I mean:
child class:
public class ChildClass extends AdultClass {
static int a=super.a+1;
}
adult class:
public class AdultClass {
static int a=5;
static public int getA() {
return a;
}
}
class that uses ChildClass object:
public class ClientClass {
public static void main(String[] args) {
ChildClass.a <-I want this to =6
ChildClass.getA() <-I want this to return 6
}
}
If you want to leverage Java's polymorphism, you'll have to involve class instances. Static members cannot display polymorphic behavior, which you apparently require from AdultClass.getA().
then simply make the member a protected one, and use it as the child's own member.
this link may be useful too.
why instance variable of super class is not overridden in sub class method

Categories