runtime polymorphism

public class child extends base
{
 int i=20;
 void m1()
 {
  System.out.println("child"+i);
 }
 public static void main(String args[])
 {
  base a =new base();
  base b=new child();
  a.m1();
  b.m1();
  System.out.println("i1:"+a.i);
  System.out.println("i2:"+b.i);
 }
}


i am getting the O/P
Base=10
Child=20
i1:10
i2:10

i thought output will be
Base=10
Child=20
i1:10
i2:20

theroitically
when we define like this
 base b=new child();

at runtime JVM will take object type not reference (here Base class)  the o/p will be i2=20 why i2 is printed 10;
LVL 20
chaitu chaituAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

baboo_Commented:
In your child class, change this:

int i = 20;

to:

child()
{
     i = 20;
}

and your problem will be solved.

baboo_
0
chaitu chaituAuthor Commented:
ohno

i forgot to paste the base class

package example;

class Base
{
 int i=10;
 void m1()
 {
  System.out.println("Base="+i);
 }
}
0
petmagdyCommented:
Chaituu,
in ur class child remove the line:

>>  int i=20;

and initialize the i in the constructor as baboo said
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

baboo_Commented:
Here's why:

Think of your child object as an onion.  On the outside layer (the "child" object layer), it has an integer variable, i, and the method, m1.  Inside that layer, the "base" class also has an integer variable, i, and a method m1.  Inside THAT layer is the ultimate base class, the Object class, which also has all of its own instance variables and methods.

Now, since you overrode the base class's m1 method with the child method m1, the JVM knows, regardless of the reference type, which method to execute - it always uses the lowest version on the inheritance tree.

But since BOTH the child AND base objects have an integer variable named i, and the reference is of type base, it's going to use base.i instead of child.i

You shouldn't declare i again in child.  It already exists in the "base" class layer, which exists within the child object layer whenever you instantiate a child object.  All you need to to is assign a value to it.  The best way to do that is to use a constructor (which is what I suggested in my last comment).

A constructor is a method you call when you use the 'new' operator.  Notice that when you create a child object, it kind of looks like you're calling a method:

base b = new child();
                       ^
                        |
See?  Looks like a method.  That's because it *is* a method - it's a constructor.  Java will provide these for you automatically if you don't write them, but you sometimes need to write them (like in your case).

Here's how you'd do it for your child class:


class child extends base
{

             child()
             {
                      // initialization stuff
                      // goes in here, like:

                       i = 20;
              }

              // the rest of the code you wrote for the child
              // class is here....
              // ...
              // ...

}

This way, there's only one integer variable named i - it exists in the base class, but your child class inherits it.  So you don't need to declare it - you can just use it as thought it was already declared (since it was, in the base class).

Anyways, I hope this helps.  Please, don't hesitate to ask me more if I haven't been completely clear about all this.

baboo_


0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
chaitu chaituAuthor Commented:
public class Child extends Base
{
int i;
Child()
{
  i =20;
}
 void m1()
 {
  System.out.println("Child="+i);
 }
 public static void main(String args[])
 {
  Base a =new Base();
  Base b=new Child();
  a.m1();
  b.m1();
  System.out.println("i1:"+a.i);
  System.out.println("i2:"+b.i);
 }
}

i changed like this still getting the same o/p

Base=10

Child=20

i1:10

i2:10
0
petmagdyCommented:
chatuu,

u didn't do what i told u i mean the following:

1- in the base class make the member field (i) protected:
protected int i;
2- in the base class intialize (i) inside the constructor
public Base()
{
i = 10;
}
3- in the child class remove the member field (i);
>> int i; // <---- remove this line
4- in the child class make the construtor as in ur last comment:

Child()
{
  i =20;
}
0
vikraman_bCommented:
Hi chatuu...
what exactly u want..?
As i told u earlier
Base a = new Base();
Base b = new Child();
a.m1();//calls base  bcos reference is base object
b.m1();//calls child bcos refernence is child object

but for member variables
a.i;//calls base class member variable
b.i;//calls base class member variable although its a child object refernce..

what the thing u want to do..?
do u want to print b.i = 20.


0
vikraman_bCommented:
what petmagdy
 told is just  to get the output
since protected member can be accessed from subclass
==========
Base=10
Child=20
i1:10
i2:20
----------------

Then in what is the meaning of runtime polymorphism??
0
baboo_Commented:
You don't need to declare the variable i in class Child because the Child class inherits the variable i from its parent class.  In fact, just declare the variable i in the Base class, and initialize it in the constructor for each class.  Here's what you need:

=== Base Class ==================

class Base
{
     int i;

      Base()
      {
           i=10;
       }

      void m1()
      {
           System.out.println("Base="+i);
      }
}

=== End Base Class ===============
=== Child Class ==================

public class Child extends Base
{

      Child()
      {
            i =20;
      }

      void m1()
      {
            System.out.println("Child="+i);
      }

      public static void main(String args[])
      {
            Base a =new Base();
            Base b=new Child();
            a.m1();
            b.m1();
            System.out.println("i1:"+a.i);
            System.out.println("i2:"+b.i);
       }
}

=== End Child Class =================
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.