What will be the output?
class A{
int i = 10;
public void printValue(){
System.out.print("Value-A");
}
}
class B extends A{
int i = 12;
public void printValue(){
System.out.print("Value-B");
}
}
public class Test{
public static void main(String args[]){
A a = new B();
a.printValue();
System.out.print(a.i);
}
}
class A{
int i = 10;
public void printValue(){
System.out.print("Value-A");
}
}
class B extends A{
int i = 12;
public void printValue(){
System.out.print("Value-B");
}
}
public class Test{
public static void main(String args[]){
A a = new B();
a.printValue();
System.out.print(a.i);
}
}
A. Value-B 11
B. Value-B 10
C. Value-A 10
D. Value-A 11
E. None of these
Answer: Option B
Solution(By Examveda Team)
If you create object of subclass with reference of super class like ( A a = new B();) then subclass method and super class variable will be executed.
Join The Discussion
Comments ( 1 )
What is method overriding in Java?
A. Redefining a superclass method in a subclass
B. Defining a new method with the same name in a subclass
C. Making a method private in a subclass
D. Hiding methods in a superclass
What is the purpose of method overloading in Java?
A. Creating static methods
B. Hiding methods in a superclass
C. Redefining methods in a subclass
D. Defining multiple methods with the same name but different parameters
A. @OverrideMethod
B. @OverrideSuper
C. @Override
D. @OverrideParent
What happens when a subclass tries to override a final method from the superclass in Java?
A. The final method is hidden
B. It results in a compilation error
C. The final method becomes static
D. The final method is hidden
import java.io.*;
class Base{
int i = 8;
static void call(){
System.out.println("Base");
}
}
class Derived extends Base{
int i = 10;
static void call(){
System.out.println("Derived");
}
}
class Derived2 extends Derived{
int i = 12;
static void call(){
System.out.println("Derived2");
}
static void call2(){
System.out.println("call2");
}
}
class Test{
public static void main (String[] args) {
Base b = new Derived2();
System.out.println(b.i);
b.call();
}
}
gives output as:
8
Base