2.2 Super Class, Sub Class, and Member Access
How Java lets us build new classes on top of existing ones using inheritance, and how access modifiers control visibility between classes.
Overview
Inheritance allows us to create new classes built upon existing ones, promoting reusability. By inheriting from an existing class, we can reuse its fields and methods while adding new functionality specific to the subclass.
Super Class vs Sub Class
Java uses the terms super class and sub class to describe the relationship between a general type and a more specific one.
Super Class
Also called a base or parent class. This is the class whose features (fields and methods) are being inherited.
Sub Class
Also called a derived or child class. It extends the super class and can add its own fields and methods.
Single Inheritance and the extends Keyword
In Java's single inheritance model, a child class extends only one parent class. The extends keyword indicates that a class is building on top of another.
// Single Inheritance Example in Java
class A {
int length;
void setLength(int l) {
length = l;
}
}
class B extends A {
int breadth;
void setBreadth(int breadth) {
this.breadth = breadth;
}
void area() {
int a = length * breadth;
System.out.println("Area = "+a);
}
}
public class SingleInheritance {
public static void main (String[] args) {
B obj = new B();
obj.setLength(5);
obj.setBreadth(4);
obj.area();
}
}Output:
Area = 20
Member Access Control
Access modifiers are part of encapsulation. They control how class members (fields and methods) are seen from other classes and packages.
| Modifier | Visibility Scope |
|---|---|
| private | Accessible only within the same class. |
| default (package-private) | Accessible only within the same package. |
| protected | Accessible within the same package and, outside the package, only in subclasses. |
| public | Accessible from anywhere in the program. |
"is-a" vs "has-a" (Composition)
Inheritance is not the only way classes relate to each other. Java also supports composition, where classes are built from other classes by holding them as fields.
- Inheritance (is-a): Represents a parent–child relationship. Example: a Car is a Vehicle.
- Composition (has-a): Represents a "has-a" relationship. Example: a Car has a steering wheel.