Part 7: Java Inheritance with real time example

JAVA | 163 comments

Java Inheritance

Subclass and Superclass contains in inheritance mainly. In Java, it is possible to inherit attributes and methods from one class to another.  It contains of two categories:

subclass (child) – the class that inherits from another class

superclass (parent) – the class being inherited from

To inherit from a class, use the extends keyword. In the example below, the Car class (subclass) inherits the attributes and methods from the Vehicle class (superclass):

Example

class Tree {
protected String leavesColor = “Green”;        // attribute
public void branch() {                    // method
System.out.println(“Tree !”);
}
}
class Fruits extends Tree {
private String fruitsName = “Mango”;    // attribute
public static void main(String[] args) {
// Create a myFruit object
Fruits myFruits = new Fruits();
// Call the () method (from the Vehicle class) on the myCar object
myFruits.branch ();
// Display the value of the brand attribute (from the Tree class) and the value of the fruitsName from the Fruits class
System.out.println(myFruits.branch + ” ” + myCar.fruitsName);
}
}

Did you notice the protected modifier in Vehicle? Here, set the brance attribute in Tree to a protected access modifier. If it was set to private, the Fruits class would not be able to access it. Why and when to Use “Inheritance”? It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.

The final Keyword

If you don’t want other classes to inherit from a class, use the final keyword:
If you try to access a final class, Java will generate an error:

final class Tree {

}
class Fruits extends Tree {

}
The output will be something like this:

Main.java:9: error: cannot inherit from final Tree
class Main extends Tree {
^
1 error)

Java inheritance refers to the capability in Java for one class to inherit from another class. In Java this is also called extending a class. One class can extend another class and thereby inherit from that class. When one class inherits from another class in Java, the two classes take on certain roles. The class that extends (inherits from another class) is the subclass and the class that is being extended (the class being inherited from) is the superclass. In other words, the subclass extends the superclass. Or, the subclass inherits from the superclass. Another commonly used term for inheritance is specialization and generalization. A subclass is a specialization of a superclass, and a superclass is a generalization of one or more subclasses.

Inheritance is a Method of Code Reuse:  Inheritance can be an effective method to share code between classes that have some traits in common, yet allowing the classes to have some parts that are different.

Class Hierarchies

In java, Superclasses and subclasses form an inheritance structure which is also called a class hierarchy. At the top of the class hierarchy you have the superclasses. At the bottom of the class hierarchy you have the subclasses. A class hierarchy may have multiple levels, meaning multiple levels of superclasses and subclasses. A subclass may itself be a superclass of other subclasses etc.

Java Inheritance Basics

When a class inherits from a superclass, it inherits parts of the superclass methods and fields. The subclass can also override (redefine) the inherited methods. Fields cannot be overridden, but can be “shadowed” in subclasses. How all this works is covered later in this text.

What is Inherited?

When a subclass extends a superclass in Java, all protected and public fields and methods of the superclass are inherited by the subclass. By inherited is meant that these fields and methods are part of of the subclass, as if the subclass had declared them itself. protected and public fields can be called and referenced just like the methods declared directly in the subclass.

Fields and methods with default (package) access modifiers can be accessed by subclasses only if the subclass is located in the same package as the superclass. Private fields and methods of the superclass can never be referenced directly by subclasses. They can, however, be referenced indirectly via methods reachable from the subclass e.g default (package), protected and public methods. Constructors are not inherited by subclasses, but a subclass constructor must call a constructor in the superclass. This will be explained in detail in a later section.

Java Only Supports Singular Inheritance

The Java inheritance mechanism only allows a Java class to inherit from a single superclass (singular inheritance). In some programming languages, like C++, it is possible for a subclass to inherit from multiple superclasses (multiple inheritance). Since multiple inheritance can create some weird problems, if e.g., the superclasses contain methods with the same names and parameters, multiple inheritance was left out in Java.

Declaring Inheritance in Java

In Java inheritance is declared using the extends keyword. You declare that one class extends another class by using the extends keyword in the class definition. Here is Java inheritance example using the extends keyword:

public class Tree {
protected String color = null;
public void colorSet (String colors) {
this.color = colors;
}
}
public class Fruits extends Tree {
int numberOftree = 0;
public String getNumberOftree() {
return this. numberOftree;
}
}

The Fruits class in this example extends the Tree class, meaning the Fruits class inherits from the Tree class. Because the Fruits class extends the Tree class, the protected field numberOftree from the Tree class is inherited by the Fruits class. When the numberOftree field is inherited, it is accessible inside a Fruits instance. The numberOftree field is not actually being referenced from the Fruits class in the code above, but it could if we wanted to. Here is an example that shows how that could look:

public class Fruits extends Tree {
int numberOftree = 0;
public String getNumberOfTrees() {
return this. numberOftree;
}
public String getnumberOftrees () {
return this.numberOftree;
}
}

The referencing happens inside the getnumberOftree () method. In many cases it would have made sense to place the getnumberOftree () method in the Tree class where the numberOftree field is located. I just placed the getnumberOftree () method in the Fruits class to show that it is possible.

Inheritance and Type Casting

It is possible to reference a subclass as an instance of one of its superclasses. For instance, using the class definitions from the example in the previous section it is possible to reference an instance of the Fruits class as an instance of the Tree class. Because the Fruits class extends (inherits from) the Tree class, it is also said to be a Tree. Here is a Java code example:

Fruits    f     = new Fruits ();
Tree tree = f;

First a Fruits  instance is created. Second, the Fruits  instance is assigned to a variable of type Tree. Now the Tree variable (reference) points to the Fruits  instance. This is possible because the Fruits class inherits from the Tree class.Because, it is possible to use an instance of some subclass as if it were an instance of its superclass. That way, you don’t need to know exactly what subclass the object is an instance of. You could treat e.g. Fruits instances as Tree instances.

The process of referencing an object of class as a different type than the class itself is called type casting. You cast an object from one type to another.

Upcasting and Downcasting

You can always cast an object of a subclass to one of its superclasses. This is referred to as upcasting (from a subclass type to a superclass type).

It may also be possible to cast an object from a superclass type to a subclass type, but only if the object really is an instance of that subclass (or an instance of a subclass of that subclass). This is referred to as downcasting (from a superclass type to a subclass type). Thus, this example of downcasting is valid:

Fruits    f     = new Fruits ();
// upcast to Tree
Tree tree = f;
// downcast to f again
Fruits    f     = (Fruits)tree;

However, the following downcast example is not valid. The Java compiler will accept it, but at runtime when this code is executed the code will throw a ClassCastException.

Truck   truck   = new Truck();
// upcast to Tree
Tree tree = truck;
// downcast to f again
Fruits    f     = (Fruits) tree;

The Truck object can be upcast to a Tree object, but it cannot be downcast to a Fruits object later. This will result in a ClassCastException.

Overriding Methods

In a subclass you can override or redefine the methods defined in the superclass. Here is a Java method override example:
public class Tree {
String treePlate = null;
public void setLicensePlate(String treePlate) {
this. treePlate = treePlate;
}
}
public class Fruits extends Tree {
public void settreePlate (String treeP) {
this.treePlate = treeP.toLowerCase();
}
}

Notice how both the Vehicle class and the Car class defines a method called settreePlate (). Now, whenever the settreePlate () method is called on a Fruits object, it is the method defined in the Fruits class that is called. The method in the superclass is ignored.

To override a method the method signature in the subclass must be the same as in the superclass. That means that the method definition in the subclass must have exactly the same name and the same number and type of parameters, and the parameters must be listed in the exact same sequence as in the superclass. Otherwise the method in the subclass will be considered a separate method.

In Java you cannot override private methods from a superclass. If the superclass calls a private method internally from some other method, it will continue to call that method from the superclass, even if you create a private method in the subclass with the same signature.

The @override Annotation

If you override a method in a subclass, and the method is accidently removed or modified in the superclass, the method in the subclass no longer overrides the method in the superclass. But how do you know? It would be nice if the compiler could tell you that the method being overridden no longer overrides a method in the superclass, right?

This is what the Java @override annotation is for. You place the Java @override annotation above the method that overrides a method in a superclass. Here is Java @override example:

public class Fruits extends Tree {
@Override
public void settreePlate (String treeP) {
this.treePlate= treeP.toLowerCase();
}
}

Calling Superclass Methods

If you override a method in a subclass, but still need to call the method defined in the superclass, you can do so using the super reference, like this:

public class Fruits extends Tree {
public void settreePlate (String treeP) {
super.settreePlate (treeP);
}
}

In the above code example the method settreePlate() in the Car class, calls the settreePlate() method in the Tree class. You can call superclass implementations from any method in a subclass, like above. It does not have to be from the overridden method itself. For instance, you could also have called super.treePlate() from a method in the Car class called updatetreePlate() which does not override the settreePlate() method.

The instanceof Instruction

Java contains an instruction named instanceof. The instanceof instruction can determine whether a given object is an instance of some class. Here is a Java instanceof example:

Fruits f = new Fruits ();
boolean isFruits = f instanceof Fruits;

After this code has been executed the isFruits variable will contain the value true.
The instanceof instruction can also be used determine if an object is a instance of a superclass of its class. Here is an instanceof example that checks if a Car object is an instance of Vehicle:

Fruits f = new Fruits ();
boolean isTree = f instanceof Tree;

Assuming that the Fruits class extends (inherits from) the Tree class, the isTree variable will contain the value true after this code is executed. A Fruits object is also a Tree object because Fruits is a subclass of Vehicle.
As you can see, the instanceof instruction can be used to explore the inheritance hierarchy. The variable type used with the instanceof instruction does not affect its outcome. Look at this instanceof example:

Fruits f = new Fruits ();
Tree tree = f;
boolean isFruits  = tree instanceof Fruits;

Even though the tree variable is of type Tree, the object it ends up pointing to in this example is a Fruits object. Therefore the tree instanceof Fruits instruction will evaluate to true. Here is the same instanceof example, but using a Truck object instead of a Fruits object:

Truck truck = new Truck();
Tree tree = truck;
boolean isFruits = tree instanceof Fruits;

After executing this code the isFruits will contain the value false. The Truck object is not a Fruits object.

Fields and Inheritance

As mentioned earlier, in Java fields cannot be overridden in a subclass. If you define a field in a subclass with the same name as a field in the superclass, the field in the subclass will hide (shadow) the field in the superclass. If the subclass tries to access the field, it will access the field in the subclass. If, however, the subclass calls up into a method in the superclass, and that method accesses the field with the same name as in the subclass, it is the field in the superclass that is accessed. Here is Java inheritance example that illustrates how fields in subclasses shadow (hides) fields in superclasses:

public class Fruits extends Tree {
int numberOftree = 0;
public String getNumberOfTrees() {
return this. numberOftree;
}
public String getnumberOftrees () {
return this.numberOftree;
}
}
public class Tree {
String treeP = null;
public void settreeP(String treePlate) {
this. treePlate = treePlate;
}
public String getTreeP() {
return treeP;
}
}
public class Fruits extends Tree {
protected String treeP = null;
@Override
public void setTreeP(String tp) {
super.setTreeP(tp);
}
@Override
public String getTreeP () {
return super.getTreeP();
}
public void updateTreeP(String tp){
this.TreeP = tp;
}
}

Notice how both classes have a TreeP field defined. Both the Tree class and Fruits class has the methods setTreeP() and getTreeP(). The methods in the Fruits class calls the corresponding methods in the Tree class. The result is, that eventually both set of methods access the treeP field in the Tree class.

The updateTreeP() method in the Car class however, accesses the treeP field directly. Thus, it accesses the treeP field of the Fruits class. Therefore, you will not get the same result if you call setTreeP() as when you call the updateTree() method.

Look at the following lines of Java code:
Fruits f = new Fruits ();
f.setTreeP(“123”);

car.updateTreeP(“abc”);

System.out.println(“tree p: ” + f.getTreeP ());

This Java code will print out the text 123.

The updateTreeP () method sets the license plate value on the TreeP field in the Fruits class. The getTreeP() method, however, returns the value of the TreeP field in the Tree class. Therefore, the value 123 which is set as value for the TreeP field in the Vehicle class via the setTreeP() method, is what is printed out.

Constructors and Inheritance

The Java inheritance mechanism does not include constructors. In other words, constructors of a superclass are not inherited by subclasses. Subclasses can still call the constructors in the superclass using the super() contruct. In fact, a subclass constructor is required to call one of the constructors in the superclass as the very first action inside the constructor body. Here is how that looks:

public class Tree {
public Tree() {
}
}
public class Fruits extends Tree{
public Fruits() {
super();
//perform other initialization here
}
}

Notice the call to super() inside the Car constructor. This super() call executes the constructor in the Vehicle class. You may have seen Java classes where the subclass constructors did not seem to call the constructors in the superclass. Maybe the superclass did not even have a constructor. However, the subclass constructors have still called superclass constructors in those case. You just could not see it. Let me explain why: If a class does not have any explicit constructor defined, the Java compiler inserts an implicit non arg constructor. Thus, a class always has a constructor. Therefore, the following version of Vehicle is equivalent to the version shown just above:
public class Tree {

}

Second, if a constructor does not explicitly call a constructor in the superclass, the Java compiler inserts an implicit call to the no-arg constructor in the superclass. That means that the following version of the Car class is actually equivalent to the version shown earlier:
public class Fruits extends Tree {
public Fruits () {
}
}

In fact, since the constructor is now empty, we could leave it out and the Java compiler would insert it, and insert an implicit call to the non arg constructor in the superclass. This is how the two classes would look then:
public class Tree {

}

public class Fruits extends Tree{

}

Even though no constructors are declared in these two classes, they both get a no-arg constructor, and the no-arg constructor in the Fruits class will call the no-arg constructor in the Vehicle class.

If the Tree class did not have a no-arg constructor, but had another constructor which takes parameters, the Java compiler would complain. The Fruits class would then be required to declare a constructor, and inside that constructor call the constructor in the Vehicle class.

Nested Classes and Inheritance

The same Java inheritance rules apply to nested classes. Nested classes which are declared private are not inherited. Nested classes with the default (package) access modifier are only accessible to subclasses if the subclass is located in the same package as the superclass. Nested classes with the protected or public access modifier are always inherited by subclasses.

Here is a nested class inheritance example:
class FruitsClass {
class MyFruitsClass {
}
}

public class MyFruitsSubclass extends MyFruitsClass {
public static void main(String[] args) {
MyFruitsSubclass subclass = new MyFruitsSubclass();
MyFruitsClass nested =  subclass.new MyFruitsClass ();
}
}

Notice how it is possible to create an instance of the nested class MyFruitsClass which is defined in the superclass (MyFruitsClass) via a reference to the subclass (MyFruitsSubclass). Final Classes and Inheritanc. A class can be declared final. Here is now that looks:
public final class MyFruitsClass {
}

A final class cannot be extended. In other words, you cannot inherit from a final class in Java.

Chapter 6: Software Testing with example Process

What is Testing? Testing is the process of evaluating a system or its component(s) with the intent to find whether it satisfies the specified requirements or not. In simple words, testing is executing a system in order to identify any gaps, errors, or missing...

Chapter – 4: Project management with Example Procedures.

Project management Software project management is an essential part of software engineering. Projects need to be managed because professional software engineering is always subject to organizational budget and schedule constraints. The project manager‘s job is to...

You may find interest following article

Chapter 6: Software Testing with example Process

What is Testing? Testing is the process of evaluating a system or its component(s) with the intent to find whether it satisfies the specified requirements or not. In simple words, testing is executing a system in order to identify any gaps, errors, or missing requirements in contrary to the actual requirements. According to ANSI/IEEE 1059 standard, Testing can be...

Chapter-5: Cost Estimation Tutorial in Software Engineering

Cost Estimation Tutorial Cost is s strategic concept in software development for the following reasons: Project management: Estimating cost is extremely crucial in carrying out project management activities such as scheduling, planning and control.Feasibility Study: Making investment decisions regarding software projects requires full cost breakdown and analysis...

Chapter – 4: Project management with Example Procedures.

Project management Software project management is an essential part of software engineering. Projects need to be managed because professional software engineering is always subject to organizational budget and schedule constraints. The project manager‘s job is to ensure that the software project meets and overcomes these constraints as well as delivering...

Chapter -3: Agile Software Development Method Process

Agile Software Development Although there are many approaches to rapid software development, they share some fundamental characteristics: The processes of specification, design, and implementation are interleaved. There is no detailed system specification, and design documentation is minimized or generated automatically by the programming environment used to...

Chapter 2: Software processes with various model

Objectives: understand the concepts of software processes and software process models;have been introduced to three generic software process models and when they might be used;know about the fundamental process activities of software requirements engineering, software development, testing, and evolution;understand why processes should be organized to cope with...

Frequency Word for IELTS Listening

Frequency Word for IELTS Listening School a. Library  WordSentence1. Shelf 2. Librarian 3. The stacks 4. Return 5. Fine 6. Magazine 7. Copier  8. Overdue  9. Reading room  10. Reference room  11. Periodical room  12. Study lounge  13. Catalogue  14....

Chapter 8: Gantt chart Project Development in SDLC

Gantt chart Project DevelopmentSchedule (project management) The project scheduleis the tool that communicates what work needs to be performed, which resources of the organization will perform the work and the timeframes in which that work needs to be performed. The project scheduleshould reflect all of the work associated with delivering the project on time....

Chapter 7: Feasibility Analysis in Software Develoment Life Cycle.

Feasibility AnalysisWhat is Feasibility Analysis?? An analysisand evaluation of a proposed project to determine if it (1) is technically feasible, (2) is feasible within the estimated cost, and (3) will be profitable for Organization. Feasibility analysis guides the organization in determining whether to proceed with the project. Feasibility analysis also identifies...

Chapter 6: Data Flow Diagram in Software Development Life Cycle.

Data Flow Diagram What is DFD? A data flow diagram (DFD) is a graphical representation of the "flow" of data through an information system, modelling its process aspects.A DFD is often used as a preliminary step to create an overview of the system, which can later be elaborated.Show users how data moves between different processes in a system. Figure 1: DFD Symbols...

Chapter 5: System request on SDLC

System Request In most organizations, project initiation begins by preparing a  system request. A  system request is a document that describes the business reasons for building a system and the value that the system is expected to provide.The project sponsor usually completes this form as part of a formal system project selection process within the...

Chapter 4: SDLC design Phase

SDLC design Phase DFD (Design Analysis)Architectural DesignUI DesignDatabase DesignProgram DesignArchitectural design (logical)Network designClient –server designClient designServer designCloud ComputingDatabase designER diagramRelational diagramDDL (not now..!!)Program design (physical)Investigating the hardware/software platformPhysical DFDData storageData...

Chapter 3: SDLC and its Life cycle Phases.

What is SDLC? The systems development life cycle (SDLC), also referred to as the application development life-cycle, is a term used in systems engineering, information systems and software engineering to describe a process for planning, creating, testing, and deploying an information system. Career Paths for System Developers Systems Development Life Cycle Building...

Chapter 2: SDLC Key Features For SYSTEMS ANALYST.

Once upon a time, software development consisted of a programmer writing code to solve a problem or automate a procedure. Nowadays, systems are so big and complex that teams of architects, analysts, programmers, testers and users must work together to create the millions of lines of custom-written code that drive our enterprises.To manage this, a number of system...

Chapter 1: System analysis and Design Overview.

System analysis, a method of studying a system by examining its component parts and their interactions. •It provides a framework in which judgments of the experts in different fields can be combined to determine what must be done, and what is the best way to accomplish it in light of current and future needs.  •The system analyst (usually a software engineer or...

Chapter 4: Concept Of Sampling, Quantization And Resolutions

Concept Of Sampling, Quantization And Resolutions Conversion of analog signal to digital signal: The output of most of the image sensors is an analog signal, and we can not apply digital processing on it because we can not store it. We can not store it because it requires infinite memory to store a signal that can have infinite values. So we have to convert an...

Chapter 3: Images and Conversions in Digital Image Process

Images And Conversions There are many type of images, and we will look in detail about different types of images, and the color distribution in them. The binary image The binary image as it name states, contain only two pixel values. 0 and 1. In our previous tutorial of bits per pixel, we have explained this in detail about the representation of pixel values to...

Chapter 2: Concept of Pixel in Digital Image Process

Concept of Pixel Pixel Pixel is the smallest element of an image. Each pixel correspond to any one value. In an 8-bit gray scale image, the value of the pixel between 0 and 255. The value of a pixel at any point correspond to the intensity of the light photons striking at that point. Each pixel store a value proportional to the light intensity at that particular...

Part 6: IELTS Academic Writing Task 1 For Diagram/Graph Vocabulary

Vocabulary to show the sequence: You must write a summary of at least 150 words in response to a specific graph (bar, line, or pie graph), table, chart, or procedure in Writing Task 1 of the IELTS Academic test (how something works, how something is done). This job assesses your ability to choose and report the most important aspects, describe and compare data,...

Part 5: IELTS Academic Writing Task 1 Formal and Informal expressions.

Formal and Informal expressions and words: You must write a summary of at least 150 words in response to a specific graph (bar, line, or pie graph), table, chart, or procedure on the IELTS Academic test (how something works, how something is done). Few more informal expressions with their formal versions are given below. Since IELTS is a formal test, your writing...