Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA inheritance ( can't find out the difference ) [duplicate]

Tags:

java

I am doing tests to prepare for OCA and I got confused, while doing this task:

class A {
   private int i = 10;

   public void f() {}
   public void g() {}
}

class B extends A {
   public int i = 20;
   public void g() {}
}

public class C {
   A a = new A(); // 1
   A b = new B(); // 2
}

So I can't understand difference between A a = new A(); and A b = new B();

I know.. this might be easy for you guys, but I cannot figure this out.

Thanks in advance

like image 694
DevyDev Avatar asked Jan 28 '26 22:01

DevyDev


2 Answers

A a = new A() creates an object A and using this object you can access f() and g() methods in class A.

A b = new B() can be done because class B extends class A. The concept here is called polymorphism. Java allows user to assign a child object (B in this case) to parent reference (A in this case). Now using the object b you can access f() of class A as well. Note that it wouldn't have been possible if you had reference to class B (if you created B b = new B()).

Further, you can access g(), but since g() is present in class B, that takes precedence. So, g() of class B gets executed.

Try this example to understand more:

class A{
   private int i = 10;
   public void  f(){System.out.println(i);}
   public void g(){System.out.println(i+"**");}
}

class B extends A{
   public int i = 20;
   public void g(){System.out.println(i+"**********");}
}

public class C{
    public static void main(String[] args) {
        A a = new A();//1
           A b = new B();//2
           a.f();
           b.f();
           b.g();
           a.g();

    }

}
like image 105
NaveenBharadwaj Avatar answered Jan 31 '26 11:01

NaveenBharadwaj


A a = new A();
Here a can access all data members and member functions of class A.
Whereas
A b = new B(); here b can access only those member of class A which are present in class B.
This concept is called upcasting and it is done to achieve abstraction in java where we want child class method to be executed by parent class.

like image 38
Gaur93 Avatar answered Jan 31 '26 11:01

Gaur93



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!