In: Computer Science
Java Question:
Which of the following statements about the reference super is true?
|
|||
|
|||
|
|||
|
Only option C is correct
a) We do not need to explicity add super before the method
invocation of the parent class. It is done automatically by the
JVM. So, even if we do not write super.methodCall(), it will still
work
Ex:
class A{
public void test() {
System.out.print("A");
}
}
class B extends A{
public void test2() {
test(); // super.test(); ----> Same thing
}
public static void main(String[] args) {
B b = new B();
b.test2();
}
}
b)
It has to be the first statement, not the last.
As, whenever object of child class is created, the constructor of
parent class should run first before any code runs for child
class.
Though we do not have to define super() explicitly, JVM does it for
us, but in the actual code, it has to be the first statement.
Ex:
- If we try to add at last, we get this error
c) As explained above, it has to be the first statement.
THIS IS RIGHT
d) We can use super at multiple places like -
- calling functions of parent class (Though Implicit)
- calling constructor of parent class.
- referring to variable of parent class
ONLY part C is right and I have explained why others are
wrong
Kindly upvote if this
helped