πŸ“š

Β >Β 

πŸ’»Β 

Β >Β 

πŸ–²

Creating Superclasses and Subclasses

2 min readβ€’december 31, 2022

Milo Chang

Milo Chang


AP Computer Science AΒ πŸ’»

130Β resources
See Units

Introduction to Inheritance

In this unit, we will mainly focus on the last two principles of object-orientated programming. In the first half of the unit, we will discussΒ inheritance, while in the second half, we will discuss polymorphism.
Inheritance is where one class, called theΒ subclass, can share methods and instance variables with another class called theΒ superclass. When we make a subclass, the subclass can use all of the methods and instance variables of the superclass with the exact same implementation without having to write these again. However, we will learn the exception to this in Topic 9.3. The subclass can also add its own methods and instance variables that are specific to the subclass. When we use inheritance, we think of a subclass as a more specific type of the superclass.
For example, let's create the superclass SchoolSubject, which contains objects like math, science, and PE, but we have a subclass called APSubject, which is a subclass of SchoolSubjects and contains objects like apCSA and apBio. Because of inheritance, all APSubject objects are also SchoolSubject objects, but this isn't true the other way around. We will discuss this more in Topic 9.5. A subclass can only inherit from one superclass. This is because of theΒ diamond problemΒ in programming. Here is how it works:
  1. Consider a class A. A is the superclass to classes B and C.
  2. Classes B and C both have a new method named coolMethod(), each with its own implementation.
  3. Class D inherits both classes B and C.
  4. We make an object d of classD and call coolMethod(). Which version of coolMethod() will be called?
Because of this problem, the people who made Java decided that each class can inherit from a maximum of one superclass. However, one class can be the superclass for many subclasses.

Making Subclasses

Making subclasses in Java is very straightforward. To make a subclass, we just add the wordsΒ extends SuperClassNameΒ to the class header of the subclass. Let's do an example. Suppose a class A is a superclass for class B, which itself is a superclass for class C, the superclass of classes D and E. Let's write the class headers of the five classes:
public class A { } public class B extends A { } public class C extends B { } public class D extends C { } public class E extends C { }


Fiveable
Fiveable
Home
Stay Connected

Β© 2023 Fiveable Inc. All rights reserved.


Β© 2023 Fiveable Inc. All rights reserved.