What will be the output?
class A{
static void method(){
System.out.println("Class A method");
}
}
class B extends A{
static void method(){
System.out.println("Class B method");
}
}
public class Test{
public static void main(String args[]){
A a = new B();
a.method();
}
}
class A{
static void method(){
System.out.println("Class A method");
}
}
class B extends A{
static void method(){
System.out.println("Class B method");
}
}
public class Test{
public static void main(String args[]){
A a = new B();
a.method();
}
}
A. Class A method
B. Class B method
C. Compilation Error
D. Runtime Error
E. None of these
Answer: Option A
Solution(By Examveda Team)
Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type. But in the above case the methods are static which means access to them is always resolved during compile time only using the compile time type information. Accessing them using object references is just an extra liberty given by the designers of Java.
Join The Discussion
Comments ( 2 )
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
rules of overriding:
1) argument list of the base class and child class method must be same.
2)private,static , final methods cannot be overriden.
3)The scope of the access modifier of the child class method must be greater than the parent class method.
eg for rule3:
class A{
public void meth(){
S.o.p("base class");
}
}
class B extends A{
private void meth(){
S.o.p("child class");
}
}
public class test{
public static void main(String args[]){
A a=new B();
a.meth();
}}
output:base class
because scope of private(i.e of child class) is smaller than public(i.e of base class method)
rules of overriding:
1) argument list of the base class and child class method must be same.
2)private,static , final methods cannot be overriden.
3)The scope of the access modifier of the child class method must be greater than the parent class method.
eg for rule3:
class A{
public void meth(){
S.o.p("base class");
}
}
class B extends A{
private void meth(){
S.o.p("child class");
}
}
public class test{
public static void main(String args[]){
A a=new B();
a.meth();
}}
output:base class
because scope of private(i.e of child class) is smaller than public(i.e of base class method)