Introduction to Inheritance in Java
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one class (the subclass) to inherit fields and methods from another class (the superclass). This promotes code reusability and establishes a natural hierarchical relationship between classes.
Key Concepts of Inheritance:
- Superclass and Subclass:
- Superclass (Parent Class): The class whose features are inherited. It provides common attributes and behaviors that can be shared by subclasses.
- Subclass (Child Class): The class that inherits from the superclass. It can extend or modify the behavior of the superclass and add its own unique features.
- Basic Syntax:
- To declare a subclass, use the
extends
keyword. ```java public class Subclass extends Superclass { // Subclass-specific fields and methods }
- To declare a subclass, use the
Topics to Explore: To learn more, you can explore the tabs on the navigation bar to explore additional units within the CollegeBoard curriculum.
public class Vehicle {
float miles = 0;
float milesTraveled(float milesToAdd){
this.miles += milesToAdd;
return this.miles;
}
boolean hasMovement = true;
}
public class Car extends Vehicle {
boolean canFly = true;
}
public class Plane extends Vehicle {
boolean canFly = true;
}
Car myCar = new Car();
System.out.println("As you can see my Car also has the inherited varible hasMovement");
System.out.println("myCar.hasMovement: "+(new Boolean(myCar.hasMovement)).toString());
As you can see my Car also has the inherited varible hasMovement
myCar.hasMovement: true