Subclass in Java Explain

Creating Subclasses

You created a Java class to model the data and operations of an Employee. Now suppose you want to specialize the data and operations to describe a Manager.

Specialization Using Java Subclassing

The Manager class shown here closely resembles the Employee class, but with some specialization. A Manager also has a department, with a department name. As a result, there are likely to be additional operations as well. 

What this demonstrates is that an Manager is an Employee- but an employee with an additional features.

Subclassing in Java

In an object-oriented language like Java , subclassing is used to define a new class in terms of an existing one.

A Simple Java Program

When an existing class is subclassed , the new class created is said to inherit the characteristics of the other class. This new class is called the subclassand is a specialization of the superclass. All of the non-private fields and  methods from the superclass are part of the subclass.

So in the diagram, a Manager class get empID , name, SSN, salary, and all of the public method from Employee.

It is important to grasp that although Manager specializes Employee , a Manager is still an Employee.

Manage Subclass

Java Syntax for Subclassing

The keyword extends is used to create a subclass.

The Manager class , by extending the Employee class, inherits all of the non- private data fields and methods from Employee. After all, if a manager is also an employee, then its follows that Manager has all of the same attributes and operations of Employee.

  • Note that manager class declares its own constructor.
  • Constructor are not inherited from the parent class.
Constructor in Subclasses

Every subclass inherits the non-private fields and methods from its parent (superclass).However, the subclass do not inherit the constructor from its parent . Its must provide a constructor.

The Java Language Specification includes the following description:

"Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding".

About Codingwelove

Recommended Posts × +


Post a Comment