Results 1 to 4 of 4
  1. #1
    javastuden's Avatar
    javastuden is offline Senior Member
    Join Date
    Nov 2009
    Posts
    160
    Rep Power
    5

    Default why the out put is 10

    Hi,
    Why the output is 10
    class Q16
    {
    public static void main(String args[])
    {
    A a = new B();
    a.callme();
    System.out.println(a.r);


    }
    }


    class A
    {
    void callme()
    {
    System.out.println("A");
    }
    int r=10;



    }
    class B extends A
    {
    public void callme()
    {
    System.out.println("B");
    }
    int r=20;


    }


    Result be
    B
    10

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Tsk, tsk... You've posted more than 30 times here and should know about using code tags.

    So this exercise makes you think a bit about the nature of polymorphism in Java -- does Java allow for polymorphism for both methods and fields or just methods alone?

  3. #3
    javastuden's Avatar
    javastuden is offline Senior Member
    Join Date
    Nov 2009
    Posts
    160
    Rep Power
    5

    Default shows the value in parent class then in subclass

    thank for your reply

    it will invoke the methods

    then

    class Earth{

    public static void main(String[] args) {
    // Earths myEarth = new Earths();
    //Planet myPlanet = (Planet)myEarth;
    Planet myPlanet=new Earths();
    myPlanet.hide();
    myPlanet.override();
    }
    }
    class Planet {
    public static void hide() {
    System.out.println("The hide method in Planet.");
    }
    public void override() {
    System.out.println("The override method in Planet.");
    }
    }

    class Earths extends Planet {
    public static void hide() {
    System.out.println("The hide method in Earth.");
    }
    public void override() {
    System.out.println("The override method in Earth.");
    }
    }

    same but different name pgm the out put is

    The hide method in Planet.
    The override method in Earth.

    why it shows the value in parent class then in subclass

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,854
    Rep Power
    19

    Default

    Because this:
    myPlanet.hide();
    is not how you should call a static method. If you called it properly, as in:
    Planet.hide();
    you would know exactly why it called Planets hide() method and not Earths.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •