Advanced Placement Computer Science A focusing on Java programming and object-oriented design.
Inheritance lets one class use the fields and methods of another. It's like a family tree for your code!
public class Animal {
void eat() {
System.out.println("Yum!");
}
}
public class Cat extends Animal {
void meow() {
System.out.println("Meow!");
}
}
Here, Cat
inherits from Animal
, so Cat
objects can both eat()
and meow()
.
Polymorphism allows you to write code that works with objects of different classes in a uniform way.
Animal pet = new Cat();
pet.eat(); // Works!
If a method exists in the parent class, any child class can use or override it.
Think of a "Vehicle" class. Cars, bikes, and buses all inherit from it but behave in their own unique ways.
A Teacher
class inherits from a Person
class and adds a teach()
method.
Using a Shape
parent class so both Circle
and Rectangle
can be used in the same drawing method.
Inheritance shares code; polymorphism lets objects act in different ways.