Thursday, June 21, 2007

static method override

A subclass cannot override methods that are declared static in the superclass. In other words, a subclass cannot override a class method. A subclass can hide a static method in the superclass by declaring a static method in the subclass with the same signature as the static method in the superclass.

Ex:
public class Test {
public static void main(String[] args){
baseClass bb = new subClass();
subClass1 ss = new subClass();

ss.testme(); //output:This is inside the sub class
bb.testme(); //output:This is inside the sub class

//Conclusion: U are able to override the testme method here.

ss.testmeStatic(); //output:This is inside the sub class static
bb.testmeStatic(); //output:This is inside the base class static

//Conclusion: U are not able to override the testmeStatic method here.
}
}
class subClass extends baseClass{
public void testme(){
System.out.println("This is inside the sub class");
}
public static void testmeStatic(){
System.out.println("This is inside the sub class static ");
}
}
class baseClass{
public void testme(){
System.out.println("This is inside the base class");
}
public static void testmeStatic(){
System.out.println("This is inside the base class static ");
}
}

No comments: