JavaBeat Certifications Certifications Kits Articles Interview Questions OCAJP 7 OCPJP 5 OCPJP 6 OCEJWCD 6 SCBCD 5.0 SCEA SCJA

Can we override static methods? What is method hiding?

Topic :
Feedback Request New QnA Print Email

Static method cannot be overridden. Look into the following code:


package javabeat.net;
public class ParentClass {
    public void method1(){
        System.out.println("Parent Method1");
    }
    public static void method2(){
        System.out.println("Parent Method2");
    }
}


package javabeat.net;
public class ChildClass extends ParentClass{
    public void method1(){
        System.out.println("Child Method1");
    }
    public static void method2(){
        System.out.println("Child Method2");
    }
}


package javabeat.net;
public class MainClass {
    public static void main(String args[]){
        ParentClass parent;
        ChildClass child = new ChildClass();
        parent = child;
        parent.method1();
        parent.method2();
    }
}

In the above the parent class defines two methods method1() and method2(). Here method1() is instance method and method2() defines static method. When child class trying to override th parent class method actually instance method only will be overridden. So, what happens to static method? Static methods will be hidden when you are mistakenly overriding it. when you override a method, you get the benefits of run-time polymorphism, and when you hide, you don't. That means when you call the parent.method2(), it will not call the child class method. Parent class method will be called.

posted by Krishna
http://tech.groups.yahoo.com/group/JavaBeat_SCJP/message/5282

Topic :
Feedback Request New QnA Print Email

All api java java 6.0 java 7.0 jdbc jsp servlet ejb jndi jms ejb 3.0 j2ee jee 5.0 jee 6.0 jsf struts spring Hibernate ajax JBoss Seam netbeans eclipse ant xml maven dojo junit javafx j2me log4j ESB JBoss Apache Quartz scjp mysql oracle gwt openjpa jmx yui google-guice android JBoss scwcd 5.0 scjp 1.5 scjp 1.6 scja scbcd 5.0

javabeat | advertise | about us | contact | useful resources
Copyright (2004 - 2013), JavaBeat