Forum Stats

  • 3,727,123 Users
  • 2,245,325 Discussions
  • 7,852,604 Comments

Discussions

Static method execution pattern in mentioned code

User_JARGP
User_JARGP Member Posts: 3 Green Ribbon

In the following code I have Demo2 class which is a subclass of Demo1.

In Demo1 class I have two methods one is non static method (method1) and another is static method (method2). I am calling a method2 inside method1.

In Demo2 class I have only one static method (method2) which is same as Demo1 static method .

My question is when I am calling a method1 using subclass object in main method why it is invoking superclass static method which is also defined in subclass?


class Demo1{

    public void method1(){

        method2();

        System.out.println("Demo1 class  non static method");

    }

    static public void method2(){

        System.out.println("Demo1 class static method");

    }

}


class Demo2 extends Demo1{

        static public void method2(){

        System.out.println("Demo2 class static method");

    }

}


public class MyClass{

    public static void main(String [] args){

        Demo2 d = new Demo2();

        d.method1();

    }

}

Tagged:
Sign In or Register to comment.