Link to home
Start Free TrialLog in
Avatar of Nandi11
Nandi11

asked on

Confusing

I have class test defined as below
class Test
            {
                  int x;
                  private static int count=0;

                  public Test()
                  {
                        ++count;
                        System.out.println ("Count: " + count);

                  }
                  public static void show() {
                  System.out.println ("Show method in Test class");
                  }

                  public static int getCount() {
                        return count;
                  }

            }

Another class Quest1 defined as below

    class Ques1 extends Test
   {
        static int ct;
      public static void show()
      {
          System.out.println("Show method in Q2 class");
     }
      public static void main(String[] args)
      {

              int x=012;
                  if ( x==10.0) { System.out.println("test" + x); }
                 Test t = new Test();
                 t.show();
                 
            System.out.println("about to instantiate Ques1");
                Ques1 q = new Ques1();
                 q.show();
                 t=q;
                 System.out.println("t:" + t);
                 System.out.println("t:" + q);
                 t.show();
                 q.show();


                 
      }
  }

I have made reference of t equal to reference of qin quest1.java
when i printed their referenced it is giving me same.
but when i called t.show() it is calling the test class method show() . I am confused. I am thinking since i made t=q i thought it will call show method of quest class instead of test class ??

Please explain me
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of aozarov
aozarov

objects is right, but just to make it clearer.
When you are calling a static method on an object the call will be done on the class of type and not the type of the instance (this is set during the compilation process).
So, because t is declared as type Test then Test.show will be called.
To check that remove the show method from Test and you will see that you get a compilation error regardless the fact that t object is an instance of a subclass of Test (Ques1)