Computer Science

Java Inheritance

Java Inheritance is a mechanism in which one class acquires the properties and behaviors of another class. It allows the creation of a new class that is a modified version of an existing class. Inheritance promotes code reusability and helps in creating a hierarchical structure of classes.

Written by Perlego with AI-assistance

12 Key excerpts on "Java Inheritance"

  • OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide
    • Jeanne Boyarsky, Scott Selikoff(Authors)
    • 2014(Publication Date)
    • Sybex
      (Publisher)
    Chapter 5 Class Design
    OCA exam objectives covered in this chapter:
    • Working with Inheritance
      • Describe inheritance and its benefits
      • Develop code that demonstrates the use of polymorphism; including overriding and object type versus reference type
      • Determine when casting is necessary
      • Use super and this to access objects and constructors
      • Use abstract classes and interfaces
    In Chapter 1, “Java Building Blocks,” we introduced the basic definition for a class in Java. In Chapter 4, “Methods and Encapsulation,” we delved into constructors, methods, and modifiers, and showed how you can use them to build more structured classes. In this chapter, we'll take things one step further and show how class structure is one of the most powerful features in the Java language.
    At its core, proper Java class design is about code reusability, increased functionality, and standardization. For example, by creating a new class that extends an existing class, you may gain access to a slew of inherited primitives, objects, and methods. Alternatively, by designing a standard interface for your application, you ensure that any class that implements the interface has certain required methods defined. Finally, by creating abstract class definitions, you're defining a platform that other developers can extend and build on top of.

    Introducing Class Inheritance

    When creating a new class in Java, you can define the class to inherit from an existing class.
    Inheritance
    is the process by which the new child subclass automatically includes any public or protected primitives, objects, or methods defined in the parent class.
    For illustrative purposes, we refer to any class that inherits from another class as a
    child class
    , or a descendent of that class. Alternatively, we refer to the class that the child inherits from as the
    parent class
  • Programming Fundamentals Using JAVA
    eBook - ePub

    Programming Fundamentals Using JAVA

    A Game Application Approach

    parent class.
    The concept of inheritance is fundamental to object oriented programming. If properly used, it can greatly reduce the time and effort required to develop a software product. For example, suppose that one of the classes specified during the design of a new program is similar to an existing class in that the existing class contains many of the data members and methods listed in the new class’s UML diagram. The best way to develop the new class would be to simply add the existing class to the program and modify and/or add to it. One approach to this would be to copy the source code of the existing class, paste the code into a new class, and then modify the copied code. A better approach would be to use the concept of inheritance.
    Although we may have been importing the existing class into our programs for many years, we may not have its source code. For example, the Java API does not contain the source code of any of the classes included in it. Rather, it contains the classes’ translated byte codes. This fact would eliminate the copy and paste alternative but not the inheritance alternative. To use the concept of inheritance, we only need the byte codes of the existing class. In addition, software engineering studies reveal that copying, pasting, and modifying code that we did not write can be more time consuming than a completely independent development of a new class. Inheritance allows us to modify an existing class that was added to a new program in a way that does not introduce the errors that are associated with the copy-paste-modify alternative.
  • OCP Oracle Certified Professional Java SE 11 Programmer I Study Guide
    • Jeanne Boyarsky, Scott Selikoff(Authors)
    • 2019(Publication Date)
    • Sybex
      (Publisher)
    Chapter 9 , “Advanced Class Design,” in which we will expand our discussion of types to include abstract classes and interfaces.

    Understanding Inheritance

    When creating a new class in Java, you can define the class as inheriting from an existing class.
    Inheritance
    is the process by which a subclass automatically includes any public or protected members of the class, including primitives, objects, or methods, defined in the parent class.
    For illustrative purposes, we refer to any class that inherits from another class as a
    subclass
    or
    child class
    , as it is considered a descendant of that class. Alternatively, we refer to the class that the child inherits from as the
    superclass
    or
    parent class
    , as it is considered an ancestor of the class. And inheritance is transitive. If child class X inherits from parent class Y, which in turn inherits from a parent class Z, then class X would be considered a subclass, or descendant, of class Z. By comparison, X is a direct descendant only of class Y, and Y is a direct descendant only of class Z.
    In the last chapter, you learned that there are four access levels: public , protected , package-private, and private . When one class inherits from a parent class, all public and protected members are automatically available as part of the child class. Package-private members are available if the child class is in the same package as the parent class. Last but not least, private members are restricted to the class they are defined in and are never available via inheritance. This doesn’t mean the parent class doesn’t have private members that can hold data or modify an object; it just means the child class has no direct reference to them.
    Let’s take a look at a simple example with the BigCat and Jaguar classes. In this example, Jaguar is a subclass or child of BigCat , making BigCat a superclass or parent of Jaguar
  • Introduction to Java Programming, 2nd Edition
    characteristics of his parents and also adds some of his own characteristics.
     
    In inheritance, a superclass acts as a general class and it contains only common characteristics . But, the classes derived from a particular superclass are defined as specialized classes, as each subclass add its own specific characteristics with the characteristics inherited from a superclass.
     
    Inheritance can be well defined with the help of hierarchy of classes. In Java, every class is inherited from a particular class named as Object (the Object class comes under the default package java.lang ). So, in the hierarchy of classes, the Object class is on the top of the hierarchy . In this hierarchy, a superclass can be a direct or an indirect superclass. The direct superclass is the class from which a subclass is explicitly inherited. The indirect superclass is the class from which a subclass is not explicitly inherited, but it is two or more than two levels up in the class hierarchy, as shown in Figure 5-1.
    Figure 5-1 Hierarchical representation of direct and indirect superclasses
     
    In Figure 5-1, three classes Manager , Programmer , and Administration explicitly inherit the properties of the Employee class. Therefore, the Employee class is known as the direct superclass of the given three subclasses. Here, the Manager subclass is acting as the superclass for the Sales Manager and Project Manager classes. Therefore, the Manager class is treated as the direct superclass and the Employee class is treated as an indirect superclass for the Sales Manager and Project Manager classes.
     
    In Java, a new class can inherit some or all characteristics of a superclass by using the extends
  • Learn Java 17 Programming
    superclass .
    Another form of relationship was defined between classes and interfaces – a class can implement an interface. Since an interface describes how you can interact with an object but not how an object responds to the interaction, different objects can behave differently while implementing the same interface.
    In Java, a class can have only one direct parent but can implement many interfaces.
    The ability to behave like any of its ancestors and adhere to multiple interfaces is called polymorphism .
    In this chapter, we will look at these OOP concepts and how they are implemented in Java. The topics discussed include the following:
    • OOP concepts
    • Class
    • Interface
    • Overloading, overriding, and hiding
    • The final variable, method, and class
    • Record and sealed classes
    • Polymorphism in action

    Technical requirements

    To be able to execute the code examples provided in this chapter, you will need the following:
    • A computer with a Microsoft Windows, Apple macOS, or Linux operating system
    • Java SE version 17 or later
    • An IDE or code editor that you prefer
    The instructions for how to set up a Java SE and IntelliJ IDEA editor were provided in Chapter 1 , Getting Started with Java 17 , of this book. The files with the code examples for this chapter are available in the GitHub repository at https://github.com/PacktPublishing/Learn-Java-17-Programming.git in the examples/src/main/java/com/packt/learnjava/ch02_oop
  • Beginning C++ Programming
    In basic terms, inheritance is when one class extends another class the class being extended is called the base class, parent class, or superclass, and the class doing the extending is called a derived class, child class, or subclass. However, there is an important concept to understand with inheritance: the relationship of the derived class to the base class. It is commonly given in terms of is-a. If the derived class is a type of base class, then the relationship is inheritance. An mp3 file is an operating system file, so if you have a os_file class, then you could legitimately derive from it to create an mp3_file class. The derived class has the functionality and state of the base class (although it may not have complete access to them, as will be explained later), so it can use the functionality of the base class. In this case, it is similar to composition. However, there are significant differences. In general, in composition, the composed object is used by the class and not exposed directly to the client of the class. With inheritance, an object of the derived class is an object of the base class, so usually the client code will see the base class functionality. However, a derived class can hide the functionality of the base class, so client code will not see the hidden base class member, and the derived class can override the base class methods and provide its own version. There is a lot of disagreement in the C++ community over whether you should use inheritance or composition to reuse code, and there are advantages and disadvantages of each. Neither is perfect and often a compromise is needed. Inheriting from a class Consider a class that wraps an operating system. This will provide lots of methods to give access to things such as the creation date, modification date, and the size of the file obtained by calling operating system functions. It could also provide methods to open the file, close the file, map the file into memory, and other useful things
  • Mastering JavaScript Object-Oriented Programming
    superclass . Apart from the naming, the inheritance concept is the same, although of course it does not seem suited to JavaScript.
    We can implement inheritance in JavaScript in various ways. Consider, for example, the following constructor of person objects: function Person() { this.name = ""; this.surname = ""; }
    In order to define a programmer as a person specialized in computer programming, we will add a new property describing its knowledge about a programming language: knownLanguage .
    A simple approach to create the programmer object that inherits properties from person is based on prototype. Here is a possible implementation: function Programmer() { this.knownLanguage = ""; } Programmer.prototype = new Person(); We will create a programmer with the following code: var programmer = new Programmer();
    We will obtain an object that has the properties of the person object (name and surname ) and the specific property of the programmer (knownLanguage ), that is, the programmer object inherits the person properties.
    This is a simple example to demonstrate that JavaScript supports the inheritance principle of Object-Oriented Programming at its basic level. Inheritance is a complex concept that has many facets and several variants in programming, many of them dependent on the used language.
    In Chapter 4 , Inheriting and Creating Mixins , we will explore more in depth how JavaScript supports inheritance, analyzing different approaches and more advanced topics such as overriding and multiple inheritance.

    Polymorphism

    In Object-Oriented Programming, polymorphism is understood in different ways, even if the basis is a common notion—the ability to handle multiple data types uniformly. Support of polymorphism brings benefits in programming that go toward the overall goal of OOP. Mainly, it reduces coupling in our application, and in some cases, allows to create more compact code.
  • OCA Java SE 8 Programmer I Certification Guide
    All living beings inherit the characteristics and behaviors of their parents. The offspring of a fly looks and behaves like a fly, and that of a lion looks and behaves like a lion. But despite being similar to their parents, all offspring are also different and unique in their own ways. In addition, a single action may have different meanings for different beings. For example, the action “eat” has different meanings for a fly than a lion. A fly eats nectar, whereas a lion eats an antelope.
    Something similar happens in Java. The concept of inheriting characteristics and behaviors from parents can be compared to classes inheriting variables and methods from a parent class. Being different and unique in one’s own way is similar to how a class can both inherit from a parent and define additional variables and methods. Single actions having different meanings can be compared to polymorphism in Java.
    In the OCA Java SE 8 Programmer I exam, you’ll be asked questions on how to implement inheritance and polymorphism and how to use classes and interfaces. Hence, this chapter covers the following:
    • Understanding and implementing inheritance
    • Developing code that demonstrates the use of polymorphism
    • Differentiating between the type of a reference and an object
    • Determining when casting is required
    • Using super and this to access objects and constructors
    • Using abstract classes and interfaces
    Passage contains an image

    6.1. Inheritance with classes

    [7.1 ] Describe inheritance and its benefits
    [7.5 ] Use abstract classes and interfaces
    When we discuss inheritance in the context of an object-oriented programming language such as Java, we talk about how a class can inherit the properties and behavior of another class. The class that inherits from another class can also define additional properties and behaviors. The exam will ask you explicit questions about the need to inherit classes and how to implement inheritance using classes.
    Let’s get started with the need to inherit classes.
    6.1.1. The need to inherit classes
    Imagine the positions Programmer and Manager within an organization. Both of these positions have a common set of properties, including name, address, and phone number. These positions also have different properties. A Programmer may be concerned with a project’s programming languages, whereas a Manager
  • The Java Workshop
    eBook - ePub

    The Java Workshop

    A Practical, No-Nonsense Introduction to Java Development

    • David Cuartielles, Andreas Göransson, Eric Foster-Johnson(Authors)
    • 2019(Publication Date)
    • Packt Publishing
      (Publisher)

    3. Object-Oriented Programming

    Overview
    In this chapter, we will consider the way in which Java implements object-oriented programming (OOP ) concepts. For these purposes, you will first practice creating and instantiating your own classes so that you can later create methods that can handle data within them. We will then take you through how to code recursive methods, and even how to override existing methods in favor of your own. By the end of the chapter, you will be fully equipped to overload the definition of methods in order to accommodate different scenarios with different parameters to the same method or constructor, and annotate code to inform the compiler about specific actions that must be taken.

    Introduction

    A Java class is a template that is used to define data types. Classes are composed of objects carrying data and methods that are used to perform operations on that data. Classes can be self-contained, extend other classes with new functionalities, or implement features from other classes. In a way, classes are categories that allow us to define what kind of data can be stored within them, as well as the ways in which that data can be handled.
    Classes tell the compiler how to build a certain object during runtime. Refer to the explanation of what objects are in the Working with Objects in Java topic.
    The basic structure of a class definition looks like this: class <name> {     fields;     methods; } Note
    Class names should start with a capital letter, as in TheClass , Animal , WordCount , or any other string that somehow expresses the main purpose of the class. If contained in a separate file, the filename containing the source should be named like the class: TheClass.java , Animal.java , and so on.

    The Anatomy of a Class

    There are different software components in classes. The following example shows a class that includes some of the main ones.
  • OCA Java SE 7 Programmer I Certification Guide
    All living beings inherit the characteristics and behaviors of their parents. The offspring of a fly looks and behaves like a fly, and that of a lion looks and behaves like a lion. But despite being similar to their parents, all offspring are also different and unique in their own ways. Additionally, a single action may have different meanings for different beings. For example, the action “eat” has different meanings for a fly and a lion. A fly eats nectar, whereas a lion eats antelope.
    Something similar happens in Java. The concept of inheriting characteristics and behaviors from parents can be compared to classes inheriting variables and methods from a parent class. Being different and unique in one’s own way is similar to how a class can both inherit from a parent and also define additional variables and methods. Single actions having different meanings can be compared to polymorphism in Java.
    In the OCA Java SE 7 Programmer I exam, you’ll be asked questions on how to implement inheritance and polymorphism and how to use classes and interfaces. Hence, this chapter covers the following:
    • Understanding and implementing inheritance
    • Developing code that demonstrates the use of polymorphism
    • Differentiating between the type of a reference and an object
    • Determining when casting is required
    • Using super and this to access objects and constructors
    • Using abstract classes and interfaces

    6.1. Inheritance with classes

    [7.1] Implement inheritance
    When we discuss inheritance in the context of an object-oriented programming language such as Java, we talk about how a class can inherit the properties and behavior of another class. The class that inherits from another class can also define additional properties and behaviors. The exam will ask you explicit questions about the need to inherit classes and how to implement inheritance using classes.
    Let’s get started with the need to inherit classes.
    6.1.1. Need to inherit classes
    Imagine the positions Programmer and Manager within an organization. Both of these positions have a common set of properties, including name, address, and phone number. These positions also have different properties. A Programmer may be concerned about a project’s programming languages, whereas a Manager
  • Java Professional Interview Guide
    eBook - ePub

    Java Professional Interview Guide

    Learn About Java Interview Questions and Practise Answering About Concurrency, JDBC, Exception Handling, Spring, and Hibernate

    One may find luxury to declare a class as private to achieve the encapsulation automatically. But, it is not permitted. The reason is obvious. If you declare a class with private, then it is not accessible to the outside world, not even to JVM, which accesses the class to load and execute the main method.

    Inheritance

    Java provides many concepts as a part of its inheritance mechanism. In fact, most of the interviewers will spend at least 60% of their interview duration on inheritance. You must be well prepared about inheritance if you want to get successful in your interview of Java. The next few pages are dedicated to inheritance-related questions.

    What is association in Java?

    When we develop an application, we deal with many objects. These objects can interact with other. In other words, the objects can utilize the services that are defined by other objects. Such type of relationship between the objects is called as an association .

    What is composition in Java?

    Designing a class is always a creative job. You define properties and behavior that control the overall working of an object. Some of the properties of an object itself can contain some behavior. Let us take an example where a car contains an engine. The engine is one of the properties of a car, but the engine itself can have its own attributes and behavior. So, we can have the engine defined as a separate class with its own properties and behavior, which can be declared as a property of the car. This concept is termed as composition or has-a-kind relation.
    The following code snippet will demonstrate how the composition can be implemented:
    1. public class Car {
    2.   String color;
    3.   Engine engine;//composition
    4.   
      public void drive () {
    5.   }
    6.   
      public void start () {
    7.   }
    8. }
    9. public class Engine {
    10.   //data member
    11.   //member functions
    12. }

    What is the difference between composition and aggregation?

    Both these are types of association in Java. Both these concepts use the other object as a part of it. But, there is one difference. Once we use composition, if we destroy the main object, the object that is associated with it also gets destroyed or not meaningful. In case of aggregation, even if we delete the main object, the other object still exists in the system.
  • Web Applications with Javascript or Java
    eBook - ePub

    Web Applications with Javascript or Java

    Volume 2: Associations and Class Hierarchies

    Part II:   Inheritance in Class Hierarchies
    Whenever an app has to manage the data of a larger number of object types, there may be various subtype (inheritance) relationships between some of the object types. Subtypes and inheritance are important elements of information models. Software applications have to implement them in a proper way, typically as part of their model layer within a model-view-controller (MVC) architecture. Unfortunately, application development frameworks do often not provide much support for dealing with class hierarchies and inheritance.

    12  Subtyping and Inheritance

    The concept of a subtype, or subclass, is a fundamental concept in natural language, mathematics, and informatics. For instance, in English, we say that a bird is an animal, or the class of all birds is a subclass of the class of all animals. In linguistics, the noun “bird” is a hyponym of the noun “animal”.
    An object type may be specialized by subtypes (for instance, Bird is specialized by Parrot) or generalized by supertypes (for instance, Bird and Mammal are generalized by Animal). Specialization and generalization are two sides of the same coin.
    A subtype inherits all features from its supertypes. When a subtype inherits attributes, associations and constraints from a supertype, this means that these features need not be repeatedly rendered for the subtype in the class diagram, but the reader of the diagram has to understand that all features of a supertype also apply to its subtypes.
    When an object type has more than one direct supertype, we have a case of multiple inheritance, which is common in conceptual modeling, but prohibited in many object-oriented programming languages, such as Java and C#, which only allow class hierarchies with a unique direct supertype for each object type.

    12.1  Introducing Subtypes by Specialization

    A new object type may be introduced by specialization whenever it represents a special case of another object type. We illustrate this for our example model where we want to capture text books and biographies as special cases of books. This means that text books and biographies also have an ISBN, a title and a publishing year, but in addition they have further features such as the attribute subjectArea for text books and the attribute about for biographies. Consequently, in Figure 12.1 , we introduce the object types TextBook and Biography by specializing the object type Book , that is, as subtypes of Book
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.