AP Computer Science A Unit 9 Review with Java coding
1. Creating Superclasses and Subclasses
Inheritance is a key concept in object-oriented programming that allows a class (subclass) to inherit properties and behaviors from another class (superclass).
// Superclass
class Animal {
String species;
void makeSound() {
System.out.println("Animal makes a sound.");
}
}
// Subclass inheriting from Animal
class Dog extends Animal {
void wagTail() {
System.out.println("Dog wags its tail.");
}
}
2. Writing Constructors for Subclasses
Constructors in subclasses can call the constructor of their superclass using the super
keyword.
class Animal {
String species;
Animal(String species) {
this.species = species;
}
}
class Dog extends Animal {
String breed;
Dog(String species, String breed) {
super(species); // Call superclass constructor
this.breed = breed;
}
}
3. Overriding Methods
Subclasses can provide a specific implementation for a method that is already defined in their superclass. This is known as method overriding.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound.");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks.");
}
}
4. super Keyword
The super
keyword in Java is used to refer to the superclass, access superclass methods and constructors, and to invoke superclass constructors.
class Animal {
String species;
Animal(String species) {
this.species = species;
}
}
class Dog extends Animal {
String breed;
Dog(String species, String breed) {
super(species); // Call superclass constructor
this.breed = breed;
}
}
5. Creating References Using Inheritance Hierarchies
References of a superclass type can be used to refer to objects of subclasses. This allows for polymorphic behavior.
Animal myAnimal = new Dog("Canine", "Golden Retriever");
6. Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass. This enables flexibility and extensibility in code.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound.");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks.");
}
}
// Polymorphic behavior
Animal myAnimal = new Dog();
myAnimal.makeSound(); // Output: "Dog barks."