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?

-
1Does this answer your question? Java Inheritance - calling superclass methoduser6073886– user60738862020-03-09 16:44:21 +00:00Commented Mar 9, 2020 at 16:44
-
1When defining the child class' method, call the parent's version using super.quality().Nathan Hughes– Nathan Hughes2020-03-09 16:45:07 +00:00Commented Mar 9, 2020 at 16:45
Add a comment
|
3 Answers
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 :)