Why do we assign a parent link to a child in Java?

I am asking a fairly simple question, but I'm a bit confused about this.

Suppose I have a Parent class:

 public class Parent { int name; } 

And another Child.java class:

 public class Child extends Parent{ int salary; } 

And finally, my Main.java class

 public class Main { public static void main(String[] args) { Parent parent = new Child(); parent.name= "abcd"; } } 

If I create a child, for example

 Child child = new Child(): 

Then the child object can access the name and salary .

My question is:

 Parent parent = new Child(); 

provides access only to the name variable of the Parent class. So what is the exact use of this line?

  Parent parent = new Child(); 

And also, when it uses dynamic polymorphism, then why the child class variable is not available after that

 Parent parent = new Child(); 
+41
java inheritance casting oop upcasting
Aug 28 2018-12-12T00:
source share
8 answers

First, clarification of the terminology: we assign the Child object to a variable of type Parent . Parent is a reference to an object that is a subtype of Parent , a Child .

This is only useful in a more complex example. Imagine that you add getEmployeeDetails to the Parent class:

 public String getEmployeeDetails() { return "Name: " + name; } 

We could override this method in Child to provide more details:

 @Override public String getEmployeeDetails() { return "Name: " + name + " Salary: " + salary; } 

Now you can write one line of code that receives any information, whether it be a Parent or Child object:

 parent.getEmployeeDetails(); 

The following code:

 Parent parent = new Parent(); parent.name = 1; Child child = new Child(); child.name = 2; child.salary = 2000; Parent[] employees = new Parent[] { parent, child }; for (Parent employee : employees) { employee.getEmployeeDetails(); } 

Result:

 Name: 1 Name: 2 Salary: 2000 

We used Child as Parent . It had specialized behavior unique to the Child class, but when we called getEmployeeDetails() , we could ignore the difference and focus on how Parent and Child are similar. This is called a subtype of polymorphism .

The updated question asks why Child.salary not available if the Child object is stored in the Parent link. The answer is the intersection of "polymorphism" and "static typing." Since Java is statically typed at compile time, you get certain guarantees from the compiler, but you have to follow the rules in exchange or the code will not compile. An appropriate guarantee here is that each instance of a subtype (e.g. Child ) can be used as an instance of its supertype (e.g. Parent ). For example, you are guaranteed that when accessing employee.getEmployeeDetails or employee.name method or field is defined for any non-empty object that can be assigned to an employee variable of type Parent . To make this guarantee, the compiler only considers this static type (mainly the variable reference type, Parent ) when deciding what you can access. Therefore, you cannot access elements defined in the runtime type, Child .

If you really want to use Child as Parent , this is a simple limitation on life, and your code will be used for Parent and all its subtypes. If this is not acceptable, enter the link type Child .

+29
Aug 28 2018-12-12T00:
source share

It allows you to access all subclasses through a common parent interface. This is useful for running common operations available in all subclasses. A better example is required:

 public class Shape { private int x, y; public void draw(); } public class Rectangle extends Shape { public void draw(); public void doRectangleAction(); } 

Now if you have:

 List<Shape> myShapes = new ArrayList<Shape>(); 

You can refer to each element in the list as a shape, you do not need to worry if it is a rectangle or some other type, for example, say "Circle". You can treat them the same way; you can draw them all. You cannot call doRectangleAction because you do not know if the Shape is really a rectangle.

This is a trade that you do between processing objects in a general way and, in particular, with special treatment.

Indeed, I think you need to know more about OOP. A good book should help: http://www.amazon.com/Design-Patterns-Explained-Perspective-Object-Oriented/dp/0201715945

+9
Aug 28 2018-12-12T00:
source share

If you assign a parent type to a subclass, this means that you agree to use the general functions of the parent class.

This gives you the freedom to abstract from different subclass implementations. As a result, you limit yourself to parenting functions.

However, this type of assignment is called upcasting.

 Parent parent = new Child(); 

The opposite is contraction.

 Child child = (Child)parent; 

So, if you create an instance of Child and drop it onto Parent , you can use the type name attribute. If you create an instance of Parent , you can do the same as in the previous case, but you cannot use salary because there is no such attribute in Parent . Return to the previous case, which may use salary , but only if downcasting on Child .

More detailed explanation

+4
Aug 28 2018-12-12T00:
source share

When compiling your program, the reference variable of the base class receives memory, and the compiler checks all the methods of this class. Therefore, it checks all the methods of the base class, but not the methods of the child class. Now at run time, when the object is created, only proven methods can be executed. If a function is overridden in a child class, this function is started. Other functions of the child class are not performed. The coz compiler did not recognize them at compile time.

+4
Jun 30
source share

Suppose you would like to have an array of instances of the parent class and a set of child classes Child1, Child2, Child3 extending Parent. There are situations when you are only interested in the implementation of the parent class, which is more general and does not care about the more specific things introduced by the child classes.

+1
Aug 28 2018-12-12T00:
source share

This situation arises when you have several implementations. Let me explain. Suppose you have several sorting algorithms, and you want to select at runtime the one you want to implement, or you want to give someone else the opportunity to add its implementation. To solve this problem, you usually create an abstract class (Parent) and have a different implementation (Child). If you write:

 Child c = new Child(); 

you bind your implementation to the Child class, and you can no longer modify it. Otherwise, if you use:

 Parent p = new Child(); 

while Child extends Parent you can change it in the future without changing the code.

The same can be done using interfaces: Parent is no longer a class, but a java interface.

In general, you can use this approach in a DAO template, where you want to have several DB-dependent implementations. You can take a look at FactoryPatter or AbstractFactory Pattern. Hope this helps you.

+1
Aug 28 2018-12-12T00:
source share

It's simple.

 Parent parent = new Child(); 

In this case, the object type is Parent . Ant Parent has only one property. This is name .

 Child child = new Child(); 

And in this case, the object type is Child . Ant Child has two properties. This is name and salary .

The fact is that there is no need to initialize a non-final field immediately after the declaration. This is usually done at runtime, because often you cannot know exactly which implementation you will need. For example, imagine you have a class hierarchy with the Transport class at the head. And three subclasses: Car , Helicopter and Boat . And there is another Tour class that has a Transport field. I.e:

 class Tour { Transport transport; } 

Until the user booked a ride and selected a specific type of transport, you cannot initialize this field. This is the first.

Secondly, suppose all these classes must have a go() method, but with a different implementation. You can define the default base implementation in the Transport superclass and your own unique implementations in each subclass. With this initialization, Transport tran; tran = new Car(); Transport tran; tran = new Car(); you can call the tran.go() method and get the result without worrying about the specific implementation. The itll method calls an overridden method from a specific subclass.

In addition, you can use an instance of a subclass wherever an instance of a superclass is used. For example, you want to provide an opportunity to rent your vehicle. If you do not use polymorphism, you need to write many methods for each case: rentCar(Car car) , rentBoat(Boat boat) , etc. At the same time, polymorphism allows you to create one universal rent(Transport transport) method. You can pass an object of any subclass of Transport into it. Also, if your logic grows over time and you need to create another class in the hierarchy? When using polymorphism, you do not need to change anything. Just add the Transport class and pass the new class to the method:

 public class Airplane extends Transport { //implementation } 

and rent(new Airplane()) . And new Airplane().go() in the second case.

+1
Aug 28 2018-12-12T00:
source share

You declare the parent as the parent, so java will only provide methods and attributes of the Parent class.

 Child child = new Child(); 

must work. Or

 Parent child = new Child(); ((Child)child).salary = 1; 
-5
Aug 28 2018-12-12T00:
source share



All Articles