The child class and parent class has the same function quality() but the functions contain a different set of code. What I've been trying to do is invoke quality() in the parent class and then the quality() of the child class only by using the object of the child class. Is it possible? If yes, could you please explain?
Asked
Active
Viewed 138 times
-4

Nikos Hidalgo
- 3,666
- 9
- 25
- 39
-
1Does this answer your question? [Java Inheritance - calling superclass method](https://stackoverflow.com/questions/6896504/java-inheritance-calling-superclass-method) – OH GOD SPIDERS Mar 09 '20 at 16:44
-
1When defining the child class' method, call the parent's version using super.quality(). – Nathan Hughes Mar 09 '20 at 16:45
3 Answers
1
You can use super
if you want to call the parent method.
Something like this:
public class Parent {
protected void foo(){
System.out.println("1");
}
}
class Child extends Parent{
@Override
protected void foo() {
System.out.println("2");
}
void bar() {
super.foo();
}
}

Léo Schneider
- 2,085
- 3
- 15
- 28
0
Yes possible using super keyword. Inside quality() of child class make a call super.quality() as first statement

Keerthi Prasad G
- 1
- 1
0
What you need to do is you need to create your parent class, give it the quality method and let your child/subclasses inherit this. In order to do that you call super() in this constructor, what this does is that it calls its parent class. It knows what your parent is because in the class name you type extends parent class name, here ill show you a quick demo!
public class A {
private static B b = new B(); //create class object so I can run it in main
//static object as im calling it from a static function
public int quality(){ //quality method //int method because im returning answer which is an integer
int answer = 1+1; //random code
return answer;
}
public static void main(String[]args){
System.out.println(b.quality());
}
}
public class B extends A { //extends calls the super class
public B(){ //constructor (super() goes here)
super(); //invoke parent class
}
@Override
public int quality(){
int answer = 2+2; //modify the code in this class by overriding it
return answer;
}
}
output = 4
any questions, ask! Im glad to help :)

Bradley Brown
- 19
- 7