0

Suppose B extends A and we have a declaration A a=new B(); What is the use of referencing sub class object by super class variable?And what are the fields and methods accessible by the object a((only child class methods and variables) Or (from both child and parent class))?

Thank u

srk
  • 427
  • 4
  • 11
  • 27

4 Answers4

1

The reason is abstraction. The idea is that you don't need to know every little tiny detail about the object. For example, say you're driving a car. For the most part, the pedal on the right makes you go faster, the pedal on the left slows you down, and the big round thing in front of you steers the car. How that happens isn't important for the driver (a.k.a. user) to know, but it is very important for those details to work properly in order for the car to actually move.

Nathan
  • 24,586
  • 4
  • 27
  • 36
  • Yes and for most important when you are using any static method in your B class then you need to use object of that class to access the property or your super class must define with static specifier – Pratik Apr 01 '13 at 12:42
0

The use of using super class reference type is that you dont have to worry about implementation class (or specific class), like List a = new ArrayList();

only methods exposed by super class will be accessible in this case.

Pratik
  • 30,639
  • 18
  • 84
  • 159
kdabir
  • 9,623
  • 3
  • 43
  • 45
0

So this is mainly to achieve: Polymorphism as well as Abstraction.

The main principal is that client coding against a higher label interface and does not worry about the low level implementation.

This gives a flexibility to change the implementation without changing the clients. And also client has a flexibility to try multiple implementations.

In your example, the members that will be accessible from a are the ones defined by the A class.

JSS
  • 2,061
  • 1
  • 20
  • 26
-1

Hi In simple words we can say that All B's are A's and not all A's are B's. That is how the whole inheritence works. It givces the required abstarction.

NightsWatch
  • 467
  • 1
  • 6
  • 16