OOP inheritance

Why does running TestClass.main () output 202 202 101?

class BaseClass
{
    int data = 101;
    public void print()
    {
        System.out.print(data + " ");
    }
    public void fun()
    {
        print();
    }
}
class SubClass extends BaseClass
{
    int data = 202;
    public void print()
    {
        System.out.print(data + " ");
    }
}
class TestClass
{
    public static void main(String[] args)
    {
        BaseClass obj = new SubClass();
        obj.print();
        obj.fun();
        System.out.print(obj.data);
    }
}

With my poor knowledge of OOP, I believe that execution should be like this:

1- obj.print (); fingerprints 202 from SubClass

2- Since obj.fun () does not exist; method in the subclass it calls the parent method, so the output should be 101

3- System.out.print (obj.data); should print 202 because the value is overridden in a subclass.

So, I think that the output will be 202 101 202, but this is not so, can you explain to me why?

+3
source share
4 answers

Since obj.fun () does not exist; method in the subclass it calls the parent method, so the output should be 101

, fun, print, print ( ).

System.out.print(obj.data); 202, .

, , obj BaseClass, data. , .

+4

,

int data = 101;

BaseClass

+2

, , . . obj SubClass, print() SubClass. .

Instead of mixing methods and variables, I would recommend that you start with simple testing on methods only. The code is basically the same, with the same Polymorphism behavior, but without variables.

class BaseClass
{
    public void print()
    {
        System.out.print(101 + " ");
    }
    public void fun()
    {
        print();
    }
}
class SubClass extends BaseClass
{
    public void print()
    {
        System.out.print(202 + " ");
    }
}
class TestClass
{
    public static void main(String[] args)
    {
        BaseClass obj = new SubClass();
        obj.print();
        obj.fun();
    }
}
+1
source

1 and 2 - the methods are polymorphic - the method of base classis to use a method of sub class, if he can , and ofc, if you have a reference to thesub class

3 - the field is not polymorphic. This is taken from the link type.

0
source

All Articles