OOP Intermediate
Inheritance
Extending Classes
You have Employee, Manager, and Developer classes. They share fields like name and salary. Instead of duplicating code, inheritance lets Manager and Developer extend Employee, inheriting its fields and methods while adding their own.
Basic inheritance
Create a subclass that extends a parent class.
// Basic Inheritance
public class Basic {
public static void main(String[] args) {
System.out.println("=== Basic Inheritance ===\n");
// Create a Dog object
Dog dog = new Dog();
String dogName = "Buddy";
dog.name = dogName;
// Dog has its own method
dog.bark();
// Dog inherits from Animal
dog.eat();
dog.sleep();
System.out.println("\n=== Accessing Inherited Fields ===");
// Inherited field
System.out.println("Dog's name: " + dog.name);
System.out.println("Dog's age: " + dog.age);
System.out.println("\n=== Cat Example ===");
Cat cat = new Cat();
String catName = "Whiskers";
cat.name = catName;
cat.meow();
cat.eat(); // Inherited
cat.sleep(); // Inherited
}
}
// Parent class (superclass)
class Animal {
String name;
int age;
void eat() {
System.out.println(name + " is eating");
}
void sleep() {
System.out.println(name + " is sleeping");
}
}
// Child class (subclass)
class Dog extends Animal {
// Dog-specific method
void bark() {
System.out.println(name + " says: Woof!");
}
}
// Another child class
class Cat extends Animal {
void meow() {
System.out.println(name + " says: Meow!");
}
}
// Basic Inheritance
public class Basic {
public static void main(String[] args) {
System.out.println("=== Basic Inheritance ===\n");
// Create a Dog object
Dog dog = new Dog();
String dogName = "Luna";
dog.name = dogName;
// Dog has its own method
dog.bark();
// Dog inherits from Animal
dog.eat();
dog.sleep();
System.out.println("\n=== Accessing Inherited Fields ===");
// Inherited field
System.out.println("Dog's name: " + dog.name);
System.out.println("Dog's age: " + dog.age);
System.out.println("\n=== Cat Example ===");
Cat cat = new Cat();
String catName = "Whiskers";
cat.name = catName;
cat.meow();
cat.eat(); // Inherited
cat.sleep(); // Inherited
}
}
// Parent class (superclass)
class Animal {
String name;
int age;
void eat() {
System.out.println(name + " is eating");
}
void sleep() {
System.out.println(name + " is sleeping");
}
}
// Child class (subclass)
class Dog extends Animal {
// Dog-specific method
void bark() {
System.out.println(name + " says: Woof!");
}
}
// Another child class
class Cat extends Animal {
void meow() {
System.out.println(name + " says: Meow!");
}
}
// Basic Inheritance
public class Basic {
public static void main(String[] args) {
System.out.println("=== Basic Inheritance ===\n");
// Create a Dog object
Dog dog = new Dog();
String dogName = "Rex";
dog.name = dogName;
// Dog has its own method
dog.bark();
// Dog inherits from Animal
dog.eat();
dog.sleep();
System.out.println("\n=== Accessing Inherited Fields ===");
// Inherited field
System.out.println("Dog's name: " + dog.name);
System.out.println("Dog's age: " + dog.age);
System.out.println("\n=== Cat Example ===");
Cat cat = new Cat();
String catName = "Whiskers";
cat.name = catName;
cat.meow();
cat.eat(); // Inherited
cat.sleep(); // Inherited
}
}
// Parent class (superclass)
class Animal {
String name;
int age;
void eat() {
System.out.println(name + " is eating");
}
void sleep() {
System.out.println(name + " is sleeping");
}
}
// Child class (subclass)
class Dog extends Animal {
// Dog-specific method
void bark() {
System.out.println(name + " says: Woof!");
}
}
// Another child class
class Cat extends Animal {
void meow() {
System.out.println(name + " says: Meow!");
}
}
// Basic Inheritance
public class Basic {
public static void main(String[] args) {
System.out.println("=== Basic Inheritance ===\n");
// Create a Dog object
Dog dog = new Dog();
String dogName = "Buddy";
dog.name = dogName;
// Dog has its own method
dog.bark();
// Dog inherits from Animal
dog.eat();
dog.sleep();
System.out.println("\n=== Accessing Inherited Fields ===");
// Inherited field
System.out.println("Dog's name: " + dog.name);
System.out.println("Dog's age: " + dog.age);
System.out.println("\n=== Cat Example ===");
Cat cat = new Cat();
String catName = "Misty";
cat.name = catName;
cat.meow();
cat.eat(); // Inherited
cat.sleep(); // Inherited
}
}
// Parent class (superclass)
class Animal {
String name;
int age;
void eat() {
System.out.println(name + " is eating");
}
void sleep() {
System.out.println(name + " is sleeping");
}
}
// Child class (subclass)
class Dog extends Animal {
// Dog-specific method
void bark() {
System.out.println(name + " says: Woof!");
}
}
// Another child class
class Cat extends Animal {
void meow() {
System.out.println(name + " says: Meow!");
}
}
// Basic Inheritance
public class Basic {
public static void main(String[] args) {
System.out.println("=== Basic Inheritance ===\n");
// Create a Dog object
Dog dog = new Dog();
String dogName = "Buddy";
dog.name = dogName;
// Dog has its own method
dog.bark();
// Dog inherits from Animal
dog.eat();
dog.sleep();
System.out.println("\n=== Accessing Inherited Fields ===");
// Inherited field
System.out.println("Dog's name: " + dog.name);
System.out.println("Dog's age: " + dog.age);
System.out.println("\n=== Cat Example ===");
Cat cat = new Cat();
String catName = "Shadow";
cat.name = catName;
cat.meow();
cat.eat(); // Inherited
cat.sleep(); // Inherited
}
}
// Parent class (superclass)
class Animal {
String name;
int age;
void eat() {
System.out.println(name + " is eating");
}
void sleep() {
System.out.println(name + " is sleeping");
}
}
// Child class (subclass)
class Dog extends Animal {
// Dog-specific method
void bark() {
System.out.println(name + " says: Woof!");
}
}
// Another child class
class Cat extends Animal {
void meow() {
System.out.println(name + " says: Meow!");
}
}
dog ← ⟨Dog A⟩, dogName ← Buddy, dog.name ← Buddy
3public class Basic {4 public static void main(String[] args) {5 System.out.println("=== Basic Inheritance ===\n");6 7 // Create a Dog object //?createdog8 Dog dog→ ⟨Dog A⟩ = new Dog();9 String dogName→ Buddy = "Buddy"; //@dogName="Luna", "Rex"10 dog.name→ Buddy = dogNameBuddy;11 12 // Dog has its own method //?ownmethod13 dog.bark();output=== Basic Inheritance ===void bark()
12 // Dog has its own method //?ownmethod13 dog.bark();14 15 // Dog inherits from Animal //?inherited16 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field //?inheritedfield22 System.out.println("Dog's name: " + dog.name);23 System.out.println("Dog's age: " + dog.age);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat = new Cat(); //?cat28 String catName = "Whiskers"; //@catName="Misty", "Shadow"29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass) //?superclass37class Animal {38 String name; //?parentfield39 int age;40 41 void eat() { //?parentmethod42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(name + " is sleeping");47 }48}4950// Child class (subclass) //?subclass51class Dog extends Animal { //?extends52 // Dog-specific method53 void bark() { //?childmethod54 System.out.println(nameBuddy + " says: Woof!");55 }outputBuddy says: Woof!void eat()
pass 1 of 215 // Dog inherits from Animal //?inherited16 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field //?inheritedfield22 System.out.println("Dog's name: " + dog.name);23 System.out.println("Dog's age: " + dog.age);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat = new Cat(); //?cat28 String catName = "Whiskers"; //@catName="Misty", "Shadow"29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass) //?superclass37class Animal {38 String name; //?parentfield39 int age;40 41 void eat() { //?parentmethod42 System.out.println(nameBuddy + " is eating");43 }outputBuddy is eatingcat ← ⟨Cat B⟩, catName ← Whiskers, cat.name ← Whiskers
pass 1 of 216 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field //?inheritedfield22 System.out.println("Dog's name: " + dog.nameBuddy);23 System.out.println("Dog's age: " + dog.age0);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat→ ⟨Cat B⟩ = new Cat(); //?cat28 String catName→ Whiskers = "Whiskers"; //@catName="Misty", "Shadow"29 cat.name→ Whiskers = catNameWhiskers;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass) //?superclass37class Animal {38 String name; //?parentfield39 int age;40 41 void eat() { //?parentmethod42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(nameBuddy + " is sleeping");47 }outputBuddy is sleeping === Accessing Inherited Fields === Dog's name: Buddy Dog's age: 0 === Cat Example ===void meow()
29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass) //?superclass37class Animal {38 String name; //?parentfield39 int age;40 41 void eat() { //?parentmethod42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(name + " is sleeping");47 }48}4950// Child class (subclass) //?subclass51class Dog extends Animal { //?extends52 // Dog-specific method53 void bark() { //?childmethod54 System.out.println(name + " says: Woof!");55 }56}5758// Another child class59class Cat extends Animal {60 void meow() {61 System.out.println(nameWhiskers + " says: Meow!");62 }outputWhiskers says: Meow!void eat()
pass 2 of 230 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass) //?superclass37class Animal {38 String name; //?parentfield39 int age;40 41 void eat() { //?parentmethod42 System.out.println(nameWhiskers + " is eating");43 }outputWhiskers is eatingvoid sleep()
pass 2 of 231 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass) //?superclass37class Animal {38 String name; //?parentfield39 int age;40 41 void eat() { //?parentmethod42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(nameWhiskers + " is sleeping");47 }outputWhiskers is sleeping
dog ← ⟨Dog A⟩, dogName ← Luna, dog.name ← Luna
3public class Basic {4 public static void main(String[] args) {5 System.out.println("=== Basic Inheritance ===\n");6 7 // Create a Dog object8 Dog dog→ ⟨Dog A⟩ = new Dog();9 String dogName→ Luna = "Luna";10 dog.name→ Luna = dogNameLuna;11 12 // Dog has its own method13 dog.bark();output=== Basic Inheritance ===void bark()
12 // Dog has its own method13 dog.bark();14 15 // Dog inherits from Animal16 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field22 System.out.println("Dog's name: " + dog.name);23 System.out.println("Dog's age: " + dog.age);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat = new Cat();28 String catName = "Whiskers";29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(name + " is sleeping");47 }48}4950// Child class (subclass)51class Dog extends Animal {52 // Dog-specific method53 void bark() {54 System.out.println(nameLuna + " says: Woof!");55 }outputLuna says: Woof!void eat()
pass 1 of 215 // Dog inherits from Animal16 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field22 System.out.println("Dog's name: " + dog.name);23 System.out.println("Dog's age: " + dog.age);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat = new Cat();28 String catName = "Whiskers";29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(nameLuna + " is eating");43 }outputLuna is eatingcat ← ⟨Cat B⟩, catName ← Whiskers, cat.name ← Whiskers
pass 1 of 216 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field22 System.out.println("Dog's name: " + dog.nameLuna);23 System.out.println("Dog's age: " + dog.age0);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat→ ⟨Cat B⟩ = new Cat();28 String catName→ Whiskers = "Whiskers";29 cat.name→ Whiskers = catNameWhiskers;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(nameLuna + " is sleeping");47 }outputLuna is sleeping === Accessing Inherited Fields === Dog's name: Luna Dog's age: 0 === Cat Example ===void meow()
29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(name + " is sleeping");47 }48}4950// Child class (subclass)51class Dog extends Animal {52 // Dog-specific method53 void bark() {54 System.out.println(name + " says: Woof!");55 }56}5758// Another child class59class Cat extends Animal {60 void meow() {61 System.out.println(nameWhiskers + " says: Meow!");62 }outputWhiskers says: Meow!void eat()
pass 2 of 230 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(nameWhiskers + " is eating");43 }outputWhiskers is eatingvoid sleep()
pass 2 of 231 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(nameWhiskers + " is sleeping");47 }outputWhiskers is sleeping
dog ← ⟨Dog A⟩, dogName ← Rex, dog.name ← Rex
3public class Basic {4 public static void main(String[] args) {5 System.out.println("=== Basic Inheritance ===\n");6 7 // Create a Dog object8 Dog dog→ ⟨Dog A⟩ = new Dog();9 String dogName→ Rex = "Rex";10 dog.name→ Rex = dogNameRex;11 12 // Dog has its own method13 dog.bark();output=== Basic Inheritance ===void bark()
12 // Dog has its own method13 dog.bark();14 15 // Dog inherits from Animal16 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field22 System.out.println("Dog's name: " + dog.name);23 System.out.println("Dog's age: " + dog.age);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat = new Cat();28 String catName = "Whiskers";29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(name + " is sleeping");47 }48}4950// Child class (subclass)51class Dog extends Animal {52 // Dog-specific method53 void bark() {54 System.out.println(nameRex + " says: Woof!");55 }outputRex says: Woof!void eat()
pass 1 of 215 // Dog inherits from Animal16 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field22 System.out.println("Dog's name: " + dog.name);23 System.out.println("Dog's age: " + dog.age);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat = new Cat();28 String catName = "Whiskers";29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(nameRex + " is eating");43 }outputRex is eatingcat ← ⟨Cat B⟩, catName ← Whiskers, cat.name ← Whiskers
pass 1 of 216 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field22 System.out.println("Dog's name: " + dog.nameRex);23 System.out.println("Dog's age: " + dog.age0);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat→ ⟨Cat B⟩ = new Cat();28 String catName→ Whiskers = "Whiskers";29 cat.name→ Whiskers = catNameWhiskers;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(nameRex + " is sleeping");47 }outputRex is sleeping === Accessing Inherited Fields === Dog's name: Rex Dog's age: 0 === Cat Example ===void meow()
29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(name + " is sleeping");47 }48}4950// Child class (subclass)51class Dog extends Animal {52 // Dog-specific method53 void bark() {54 System.out.println(name + " says: Woof!");55 }56}5758// Another child class59class Cat extends Animal {60 void meow() {61 System.out.println(nameWhiskers + " says: Meow!");62 }outputWhiskers says: Meow!void eat()
pass 2 of 230 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(nameWhiskers + " is eating");43 }outputWhiskers is eatingvoid sleep()
pass 2 of 231 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(nameWhiskers + " is sleeping");47 }outputWhiskers is sleeping
dog ← ⟨Dog A⟩, dogName ← Buddy, dog.name ← Buddy
3public class Basic {4 public static void main(String[] args) {5 System.out.println("=== Basic Inheritance ===\n");6 7 // Create a Dog object8 Dog dog→ ⟨Dog A⟩ = new Dog();9 String dogName→ Buddy = "Buddy";10 dog.name→ Buddy = dogNameBuddy;11 12 // Dog has its own method13 dog.bark();output=== Basic Inheritance ===void bark()
12 // Dog has its own method13 dog.bark();14 15 // Dog inherits from Animal16 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field22 System.out.println("Dog's name: " + dog.name);23 System.out.println("Dog's age: " + dog.age);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat = new Cat();28 String catName = "Misty";29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(name + " is sleeping");47 }48}4950// Child class (subclass)51class Dog extends Animal {52 // Dog-specific method53 void bark() {54 System.out.println(nameBuddy + " says: Woof!");55 }outputBuddy says: Woof!void eat()
pass 1 of 215 // Dog inherits from Animal16 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field22 System.out.println("Dog's name: " + dog.name);23 System.out.println("Dog's age: " + dog.age);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat = new Cat();28 String catName = "Misty";29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(nameBuddy + " is eating");43 }outputBuddy is eatingcat ← ⟨Cat B⟩, catName ← Misty, cat.name ← Misty
pass 1 of 216 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field22 System.out.println("Dog's name: " + dog.nameBuddy);23 System.out.println("Dog's age: " + dog.age0);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat→ ⟨Cat B⟩ = new Cat();28 String catName→ Misty = "Misty";29 cat.name→ Misty = catNameMisty;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(nameBuddy + " is sleeping");47 }outputBuddy is sleeping === Accessing Inherited Fields === Dog's name: Buddy Dog's age: 0 === Cat Example ===void meow()
29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(name + " is sleeping");47 }48}4950// Child class (subclass)51class Dog extends Animal {52 // Dog-specific method53 void bark() {54 System.out.println(name + " says: Woof!");55 }56}5758// Another child class59class Cat extends Animal {60 void meow() {61 System.out.println(nameMisty + " says: Meow!");62 }outputMisty says: Meow!void eat()
pass 2 of 230 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(nameMisty + " is eating");43 }outputMisty is eatingvoid sleep()
pass 2 of 231 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(nameMisty + " is sleeping");47 }outputMisty is sleeping
dog ← ⟨Dog A⟩, dogName ← Buddy, dog.name ← Buddy
3public class Basic {4 public static void main(String[] args) {5 System.out.println("=== Basic Inheritance ===\n");6 7 // Create a Dog object8 Dog dog→ ⟨Dog A⟩ = new Dog();9 String dogName→ Buddy = "Buddy";10 dog.name→ Buddy = dogNameBuddy;11 12 // Dog has its own method13 dog.bark();output=== Basic Inheritance ===void bark()
12 // Dog has its own method13 dog.bark();14 15 // Dog inherits from Animal16 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field22 System.out.println("Dog's name: " + dog.name);23 System.out.println("Dog's age: " + dog.age);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat = new Cat();28 String catName = "Shadow";29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(name + " is sleeping");47 }48}4950// Child class (subclass)51class Dog extends Animal {52 // Dog-specific method53 void bark() {54 System.out.println(nameBuddy + " says: Woof!");55 }outputBuddy says: Woof!void eat()
pass 1 of 215 // Dog inherits from Animal16 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field22 System.out.println("Dog's name: " + dog.name);23 System.out.println("Dog's age: " + dog.age);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat = new Cat();28 String catName = "Shadow";29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(nameBuddy + " is eating");43 }outputBuddy is eatingcat ← ⟨Cat B⟩, catName ← Shadow, cat.name ← Shadow
pass 1 of 216 dog.eat();17 dog.sleep();18 19 System.out.println("\n=== Accessing Inherited Fields ===");20 21 // Inherited field22 System.out.println("Dog's name: " + dog.nameBuddy);23 System.out.println("Dog's age: " + dog.age0);24 25 System.out.println("\n=== Cat Example ===");26 27 Cat cat→ ⟨Cat B⟩ = new Cat();28 String catName→ Shadow = "Shadow";29 cat.name→ Shadow = catNameShadow;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(nameBuddy + " is sleeping");47 }outputBuddy is sleeping === Accessing Inherited Fields === Dog's name: Buddy Dog's age: 0 === Cat Example ===void meow()
29 cat.name = catName;30 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(name + " is sleeping");47 }48}4950// Child class (subclass)51class Dog extends Animal {52 // Dog-specific method53 void bark() {54 System.out.println(name + " says: Woof!");55 }56}5758// Another child class59class Cat extends Animal {60 void meow() {61 System.out.println(nameShadow + " says: Meow!");62 }outputShadow says: Meow!void eat()
pass 2 of 230 cat.meow();31 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(nameShadow + " is eating");43 }outputShadow is eatingvoid sleep()
pass 2 of 231 cat.eat(); // Inherited32 cat.sleep(); // Inherited33 }34}3536// Parent class (superclass)37class Animal {38 String name;39 int age;40 41 void eat() {42 System.out.println(name + " is eating");43 }44 45 void sleep() {46 System.out.println(nameShadow + " is sleeping");47 }outputShadow is sleeping
class Child extends Parent inherits all non-private members from Parent.
Call parent constructor
Initialize parent class fields with super().
// Calling Parent Constructor with super()
public class SuperConstructor {
public static void main(String[] args) {
System.out.println("=== super() Constructor Call ===\n");
// Create Employee
Employee emp = new Employee("Alice", 30);
emp.displayInfo();
System.out.println("\n=== Manager (extends Employee) ===");
// Create Manager
Manager mgr = new Manager("Bob", 45, "Engineering");
mgr.displayInfo();
System.out.println("\n=== Developer (extends Employee) ===");
Developer dev = new Developer("Carol", 28, "Java");
dev.displayInfo();
System.out.println("\n=== Constructor Call Order ===");
System.out.println("Creating new Manager...");
Manager mgr2 = new Manager("Dan", 35, "Sales");
}
}
// Parent class
class Person {
String name;
int age;
Person(String name, int age) {
System.out.println(" Person constructor called");
this.name = name;
this.age = age;
}
}
// Child class
class Employee extends Person {
int employeeId;
static int nextId = 1000;
Employee(String name, int age) {
super(name, age);
System.out.println(" Employee constructor called");
this.employeeId = nextId++;
}
void displayInfo() {
System.out.println("Employee: " + name + ", Age: " + age + ", ID: " + employeeId);
}
}
// Grandchild class
class Manager extends Employee {
String department;
Manager(String name, int age, String department) {
super(name, age);
System.out.println(" Manager constructor called");
this.department = department;
}
@Override
void displayInfo() {
System.out.println("Manager: " + name + ", Age: " + age +
", ID: " + employeeId + ", Dept: " + department);
}
}
class Developer extends Employee {
String language;
Developer(String name, int age, String language) {
super(name, age); // Calls Employee constructor
this.language = language;
}
@Override
void displayInfo() {
System.out.println("Developer: " + name + ", Age: " + age +
", ID: " + employeeId + ", Lang: " + language);
}
}
public static void main(String[] args)
3public class SuperConstructor {4 public static void main(String[] args) {5 System.out.println("=== super() Constructor Call ===\n");6 7 // Create Employee //?createemp8 Employee emp = new Employee("Alice", 30);9 emp.displayInfo();output=== super() Constructor Call ===this.name ← Alice, this.age ← 30
pass 1 of 434Person(String nameAlice, int age30) { //?personconstructor35 System.out.println(" Person constructor called");36 this.name→ Alice = nameAlice;37 this.age→ 30 = age30;38}output Person constructor calledAll 4 passes — pass 1 is the card above pass nameageemployeeIddepartmentlanguagethis.namethis.agethis.departmentmgrthis.languagedevmgr21 Alice 30 1000 — — Alice 30 — — — — — 2 Bob 45 1001 Engineering — Bob 45 Engineering ⟨Manager A⟩ — — — 3 Carol 28 1002 — Java Carol 28 — — Java ⟨Developer B⟩ — 4 Dan 35 — Sales — Dan 35 Sales — — — ⟨Manager C⟩ nextId ← 1001, this.employeeId ← 1000, emp ← ⟨Employee D⟩
pass 1 of 47 // Create Employee //?createemp8 Employee emp→ ⟨Employee D⟩ = new Employee("Alice", 30);9 emp.displayInfo();10 11 System.out.println("\n=== Manager (extends Employee) ===");12 13 // Create Manager //?createmgr14 Manager mgr = new Manager("Bob", 45, "Engineering");15 mgr.displayInfo();16 17 System.out.println("\n=== Developer (extends Employee) ===");18 19 Developer dev = new Developer("Carol", 28, "Java"); //?createdev20 dev.displayInfo();21 22 System.out.println("\n=== Constructor Call Order ===");23 24 System.out.println("Creating new Manager...");25 Manager mgr2 = new Manager("Dan", 35, "Sales"); //?order26 }27}2829// Parent class30class Person {31 String name;32 int age;33 34 Person(String name, int age) { //?personconstructor35 System.out.println(" Person constructor called");36 this.name = name;37 this.age = age;38 }39}4041// Child class42class Employee extends Person {43 int employeeId;44 static int nextId = 1000;45 46 Employee(String nameAlice, int age30) { //?empconstructor47 super(name, age); //?supercall48 System.out.println(" Employee constructor called");49 this.employeeId→ 1000 = nextId→ 1001++;50 }output Employee constructor calledAll 4 passes — pass 1 is the card above pass nameageemployeeIddepartmentlanguagenextIdthis.employeeIdempthis.departmentmgrthis.languagedevmgr21 Alice 30 1000 — — 1000 → 1001 1000 ⟨Employee D⟩ — — — — — 2 Bob 45 1001 Engineering — 1001 → 1002 1001 — Engineering ⟨Manager A⟩ — — — 3 Carol 28 1002 — Java 1002 → 1003 1002 — — — Java ⟨Developer B⟩ — 4 Dan 35 — Sales — 1003 → 1004 1003 — Sales — — — ⟨Manager C⟩ void displayInfo()
8 Employee emp = new Employee("Alice", 30);9 emp.displayInfo();10 11 System.out.println("\n=== Manager (extends Employee) ===");12 13 // Create Manager //?createmgr14 Manager mgr = new Manager("Bob", 45, "Engineering");15 mgr.displayInfo();16 17 System.out.println("\n=== Developer (extends Employee) ===");18 19 Developer dev = new Developer("Carol", 28, "Java"); //?createdev20 dev.displayInfo();21 22 System.out.println("\n=== Constructor Call Order ===");23 24 System.out.println("Creating new Manager...");25 Manager mgr2 = new Manager("Dan", 35, "Sales"); //?order26 }27}2829// Parent class30class Person {31 String name;32 int age;33 34 Person(String name, int age) { //?personconstructor35 System.out.println(" Person constructor called");36 this.name = name;37 this.age = age;38 }39}4041// Child class42class Employee extends Person {43 int employeeId;44 static int nextId = 1000;45 46 Employee(String name, int age) { //?empconstructor47 super(name, age); //?supercall48 System.out.println(" Employee constructor called");49 this.employeeId = nextId++;50 }51 52 void displayInfo() {53 System.out.println("Employee: " + nameAlice + ", Age: " + age30 + ", ID: " + employeeId1000);54 }outputEmployee: Alice, Age: 30, ID: 1000 === Manager (extends Employee) ===this.department ← Engineering, mgr ← ⟨Manager A⟩
pass 1 of 213 // Create Manager //?createmgr14 Manager mgr→ ⟨Manager A⟩ = new Manager("Bob", 45, "Engineering");15 mgr.displayInfo();16 17 System.out.println("\n=== Developer (extends Employee) ===");18 19 Developer dev = new Developer("Carol", 28, "Java"); //?createdev20 dev.displayInfo();21 22 System.out.println("\n=== Constructor Call Order ===");23 24 System.out.println("Creating new Manager...");25 Manager mgr2 = new Manager("Dan", 35, "Sales"); //?order26 }27}2829// Parent class30class Person {31 String name;32 int age;33 34 Person(String name, int age) { //?personconstructor35 System.out.println(" Person constructor called");36 this.name = name;37 this.age = age;38 }39}4041// Child class42class Employee extends Person {43 int employeeId;44 static int nextId = 1000;45 46 Employee(String name, int age) { //?empconstructor47 super(name, age); //?supercall48 System.out.println(" Employee constructor called");49 this.employeeId = nextId++;50 }51 52 void displayInfo() {53 System.out.println("Employee: " + name + ", Age: " + age + ", ID: " + employeeId);54 }55}5657// Grandchild class58class Manager extends Employee {59 String department;60 61 Manager(String nameBob, int age45, String departmentEngineering) { //?mgrconstructor62 super(name, age); //?superemployee63 System.out.println(" Manager constructor called");64 this.department→ Engineering = departmentEngineering;65 }output Manager constructor called@Override void displayInfo()
14 Manager mgr = new Manager("Bob", 45, "Engineering");15 mgr.displayInfo();16 17 System.out.println("\n=== Developer (extends Employee) ===");18 19 Developer dev = new Developer("Carol", 28, "Java"); //?createdev20 dev.displayInfo();21 22 System.out.println("\n=== Constructor Call Order ===");23 24 System.out.println("Creating new Manager...");25 Manager mgr2 = new Manager("Dan", 35, "Sales"); //?order26 }27}2829// Parent class30class Person {31 String name;32 int age;33 34 Person(String name, int age) { //?personconstructor35 System.out.println(" Person constructor called");36 this.name = name;37 this.age = age;38 }39}4041// Child class42class Employee extends Person {43 int employeeId;44 static int nextId = 1000;45 46 Employee(String name, int age) { //?empconstructor47 super(name, age); //?supercall48 System.out.println(" Employee constructor called");49 this.employeeId = nextId++;50 }51 52 void displayInfo() {53 System.out.println("Employee: " + name + ", Age: " + age + ", ID: " + employeeId);54 }55}5657// Grandchild class58class Manager extends Employee {59 String department;60 61 Manager(String name, int age, String department) { //?mgrconstructor62 super(name, age); //?superemployee63 System.out.println(" Manager constructor called");64 this.department = department;65 }66 67 @Override68 void displayInfo() {69 System.out.println("Manager: " + nameBob + ", Age: " + age45 + 70 ", ID: " + employeeId1001 + ", Dept: " + departmentEngineering);71 }outputManager: Bob, Age: 45, ID: 1001, Dept: Engineering === Developer (extends Employee) ===this.language ← Java, dev ← ⟨Developer B⟩
19 Developer dev→ ⟨Developer B⟩ = new Developer("Carol", 28, "Java"); //?createdev20 dev.displayInfo();21 22 System.out.println("\n=== Constructor Call Order ===");23 24 System.out.println("Creating new Manager...");25 Manager mgr2 = new Manager("Dan", 35, "Sales"); //?order26 }27}2829// Parent class30class Person {31 String name;32 int age;33 34 Person(String name, int age) { //?personconstructor35 System.out.println(" Person constructor called");36 this.name = name;37 this.age = age;38 }39}4041// Child class42class Employee extends Person {43 int employeeId;44 static int nextId = 1000;45 46 Employee(String name, int age) { //?empconstructor47 super(name, age); //?supercall48 System.out.println(" Employee constructor called");49 this.employeeId = nextId++;50 }51 52 void displayInfo() {53 System.out.println("Employee: " + name + ", Age: " + age + ", ID: " + employeeId);54 }55}5657// Grandchild class58class Manager extends Employee {59 String department;60 61 Manager(String name, int age, String department) { //?mgrconstructor62 super(name, age); //?superemployee63 System.out.println(" Manager constructor called");64 this.department = department;65 }66 67 @Override68 void displayInfo() {69 System.out.println("Manager: " + name + ", Age: " + age + 70 ", ID: " + employeeId + ", Dept: " + department);71 }72}7374class Developer extends Employee {75 String language;76 77 Developer(String nameCarol, int age28, String languageJava) { //?devconstructor78 super(name, age); // Calls Employee constructor79 this.language→ Java = languageJava;80 }@Override void displayInfo()
19 Developer dev = new Developer("Carol", 28, "Java"); //?createdev20 dev.displayInfo();21 22 System.out.println("\n=== Constructor Call Order ===");23 24 System.out.println("Creating new Manager...");25 Manager mgr2 = new Manager("Dan", 35, "Sales"); //?order26 }27}2829// Parent class30class Person {31 String name;32 int age;33 34 Person(String name, int age) { //?personconstructor35 System.out.println(" Person constructor called");36 this.name = name;37 this.age = age;38 }39}4041// Child class42class Employee extends Person {43 int employeeId;44 static int nextId = 1000;45 46 Employee(String name, int age) { //?empconstructor47 super(name, age); //?supercall48 System.out.println(" Employee constructor called");49 this.employeeId = nextId++;50 }51 52 void displayInfo() {53 System.out.println("Employee: " + name + ", Age: " + age + ", ID: " + employeeId);54 }55}5657// Grandchild class58class Manager extends Employee {59 String department;60 61 Manager(String name, int age, String department) { //?mgrconstructor62 super(name, age); //?superemployee63 System.out.println(" Manager constructor called");64 this.department = department;65 }66 67 @Override68 void displayInfo() {69 System.out.println("Manager: " + name + ", Age: " + age + 70 ", ID: " + employeeId + ", Dept: " + department);71 }72}7374class Developer extends Employee {75 String language;76 77 Developer(String name, int age, String language) { //?devconstructor78 super(name, age); // Calls Employee constructor79 this.language = language;80 }81 82 @Override83 void displayInfo() {84 System.out.println("Developer: " + nameCarol + ", Age: " + age28 + 85 ", ID: " + employeeId1002 + ", Lang: " + languageJava);86 }outputDeveloper: Carol, Age: 28, ID: 1002, Lang: Java === Constructor Call Order === Creating new Manager...this.department ← Sales, mgr2 ← ⟨Manager C⟩
pass 2 of 224 System.out.println("Creating new Manager...");25 Manager mgr2→ ⟨Manager C⟩ = new Manager("Dan", 35, "Sales"); //?order26 }27}2829// Parent class30class Person {31 String name;32 int age;33 34 Person(String name, int age) { //?personconstructor35 System.out.println(" Person constructor called");36 this.name = name;37 this.age = age;38 }39}4041// Child class42class Employee extends Person {43 int employeeId;44 static int nextId = 1000;45 46 Employee(String name, int age) { //?empconstructor47 super(name, age); //?supercall48 System.out.println(" Employee constructor called");49 this.employeeId = nextId++;50 }51 52 void displayInfo() {53 System.out.println("Employee: " + name + ", Age: " + age + ", ID: " + employeeId);54 }55}5657// Grandchild class58class Manager extends Employee {59 String department;60 61 Manager(String nameDan, int age35, String departmentSales) { //?mgrconstructor62 super(name, age); //?superemployee63 System.out.println(" Manager constructor called");64 this.department→ Sales = departmentSales;65 }output Manager constructor called
super(args) calls parent constructor. Must be first statement.
Override parent methods
Replace parent behavior in subclass.
// Method Overriding
public class MethodOverride {
public static void main(String[] args) {
System.out.println("=== Method Overriding ===\n");
Animal animal = new Animal("Generic Animal");
animal.makeSound();
animal.move();
System.out.println("\n=== Dog Override ===");
Dog dog = new Dog("Buddy");
dog.makeSound(); // Overridden
dog.move(); // Inherited (not overridden)
System.out.println("\n=== Bird Override ===");
Bird bird = new Bird("Tweety");
bird.makeSound(); // Overridden
bird.move(); // Overridden
System.out.println("\n=== Calling Parent Method with super ===");
Cat cat = new Cat("Whiskers");
cat.makeSound();
}
}
class Animal {
String name;
Animal(String name) {
this.name = name;
}
void makeSound() {
System.out.println(name + " makes a sound");
}
void move() {
System.out.println(name + " moves around");
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
@Override
void makeSound() {
System.out.println(name + " barks: Woof! Woof!");
}
// move() is inherited as-is
}
class Bird extends Animal {
Bird(String name) {
super(name);
}
@Override
void makeSound() {
System.out.println(name + " chirps: Tweet! Tweet!");
}
@Override
void move() {
System.out.println(name + " flies through the air");
}
}
class Cat extends Animal {
Cat(String name) {
super(name);
}
@Override
void makeSound() {
super.makeSound();
System.out.println(name + " also meows: Meow!");
}
}
public static void main(String[] args)
3public class MethodOverride {4 public static void main(String[] args) {5 System.out.println("=== Method Overriding ===\n");6 7 Animal animal = new Animal("Generic Animal"); //?createanimal8 animal.makeSound();output=== Method Overriding ===this.name ← Generic Animal, animal ← ⟨Animal A⟩
pass 1 of 47 Animal animal→ ⟨Animal A⟩ = new Animal("Generic Animal"); //?createanimal8 animal.makeSound();9 animal.move();10 11 System.out.println("\n=== Dog Override ===");12 13 Dog dog = new Dog("Buddy"); //?createdog14 dog.makeSound(); // Overridden //?calloverride15 dog.move(); // Inherited (not overridden)16 17 System.out.println("\n=== Bird Override ===");18 19 Bird bird = new Bird("Tweety");20 bird.makeSound(); // Overridden21 bird.move(); // Overridden //?birdmove22 23 System.out.println("\n=== Calling Parent Method with super ===");24 25 Cat cat = new Cat("Whiskers");26 cat.makeSound(); //?supermethod27 }28}2930class Animal {31 String name;32 33 Animal(String nameGeneric Animal) {34 this.name→ Generic Animal = nameGeneric Animal;35 }All 4 passes — pass 1 is the card above pass namethis.nameanimaldogbirdcat1 Generic Animal Generic Animal ⟨Animal A⟩ — — — 2 Buddy Buddy — ⟨Dog B⟩ — — 3 Tweety Tweety — — ⟨Bird C⟩ — 4 Whiskers Whiskers — — — ⟨Cat D⟩ void makeSound()
pass 1 of 27 Animal animal = new Animal("Generic Animal"); //?createanimal8 animal.makeSound();9 animal.move();10 11 System.out.println("\n=== Dog Override ===");12 13 Dog dog = new Dog("Buddy"); //?createdog14 dog.makeSound(); // Overridden //?calloverride15 dog.move(); // Inherited (not overridden)16 17 System.out.println("\n=== Bird Override ===");18 19 Bird bird = new Bird("Tweety");20 bird.makeSound(); // Overridden21 bird.move(); // Overridden //?birdmove22 23 System.out.println("\n=== Calling Parent Method with super ===");24 25 Cat cat = new Cat("Whiskers");26 cat.makeSound(); //?supermethod27 }28}2930class Animal {31 String name;32 33 Animal(String name) {34 this.name = name;35 }36 37 void makeSound() { //?parentmakesound38 System.out.println(nameGeneric Animal + " makes a sound");39 }outputGeneric Animal makes a soundvoid move()
pass 1 of 28 animal.makeSound();9 animal.move();10 11 System.out.println("\n=== Dog Override ===");12 13 Dog dog = new Dog("Buddy"); //?createdog14 dog.makeSound(); // Overridden //?calloverride15 dog.move(); // Inherited (not overridden)16 17 System.out.println("\n=== Bird Override ===");18 19 Bird bird = new Bird("Tweety");20 bird.makeSound(); // Overridden21 bird.move(); // Overridden //?birdmove22 23 System.out.println("\n=== Calling Parent Method with super ===");24 25 Cat cat = new Cat("Whiskers");26 cat.makeSound(); //?supermethod27 }28}2930class Animal {31 String name;32 33 Animal(String name) {34 this.name = name;35 }36 37 void makeSound() { //?parentmakesound38 System.out.println(name + " makes a sound");39 }40 41 void move() {42 System.out.println(nameGeneric Animal + " moves around");43 }outputGeneric Animal moves around === Dog Override ===dog ← ⟨Dog B⟩
13 Dog dog→ ⟨Dog B⟩ = new Dog("Buddy"); //?createdog14 dog.makeSound(); // Overridden //?calloverride15 dog.move(); // Inherited (not overridden)16 17 System.out.println("\n=== Bird Override ===");18 19 Bird bird = new Bird("Tweety");20 bird.makeSound(); // Overridden21 bird.move(); // Overridden //?birdmove22 23 System.out.println("\n=== Calling Parent Method with super ===");24 25 Cat cat = new Cat("Whiskers");26 cat.makeSound(); //?supermethod27 }28}2930class Animal {31 String name;32 33 Animal(String name) {34 this.name = name;35 }36 37 void makeSound() { //?parentmakesound38 System.out.println(name + " makes a sound");39 }40 41 void move() {42 System.out.println(name + " moves around");43 }44}4546class Dog extends Animal {47 Dog(String nameBuddy) {48 super(name);@Override //?override void makeSound()
13 Dog dog = new Dog("Buddy"); //?createdog14 dog.makeSound(); // Overridden //?calloverride15 dog.move(); // Inherited (not overridden)16 17 System.out.println("\n=== Bird Override ===");18 19 Bird bird = new Bird("Tweety");20 bird.makeSound(); // Overridden21 bird.move(); // Overridden //?birdmove22 23 System.out.println("\n=== Calling Parent Method with super ===");24 25 Cat cat = new Cat("Whiskers");26 cat.makeSound(); //?supermethod27 }28}2930class Animal {31 String name;32 33 Animal(String name) {34 this.name = name;35 }36 37 void makeSound() { //?parentmakesound38 System.out.println(name + " makes a sound");39 }40 41 void move() {42 System.out.println(name + " moves around");43 }44}4546class Dog extends Animal {47 Dog(String name) {48 super(name);49 }50 51 @Override //?override52 void makeSound() { //?dogmakesound53 System.out.println(nameBuddy + " barks: Woof! Woof!");54 }outputBuddy barks: Woof! Woof!void move()
pass 2 of 214 dog.makeSound(); // Overridden //?calloverride15 dog.move(); // Inherited (not overridden)16 17 System.out.println("\n=== Bird Override ===");18 19 Bird bird = new Bird("Tweety");20 bird.makeSound(); // Overridden21 bird.move(); // Overridden //?birdmove22 23 System.out.println("\n=== Calling Parent Method with super ===");24 25 Cat cat = new Cat("Whiskers");26 cat.makeSound(); //?supermethod27 }28}2930class Animal {31 String name;32 33 Animal(String name) {34 this.name = name;35 }36 37 void makeSound() { //?parentmakesound38 System.out.println(name + " makes a sound");39 }40 41 void move() {42 System.out.println(nameBuddy + " moves around");43 }outputBuddy moves around === Bird Override ===bird ← ⟨Bird C⟩
19 Bird bird→ ⟨Bird C⟩ = new Bird("Tweety");20 bird.makeSound(); // Overridden21 bird.move(); // Overridden //?birdmove22 23 System.out.println("\n=== Calling Parent Method with super ===");24 25 Cat cat = new Cat("Whiskers");26 cat.makeSound(); //?supermethod27 }28}2930class Animal {31 String name;32 33 Animal(String name) {34 this.name = name;35 }36 37 void makeSound() { //?parentmakesound38 System.out.println(name + " makes a sound");39 }40 41 void move() {42 System.out.println(name + " moves around");43 }44}4546class Dog extends Animal {47 Dog(String name) {48 super(name);49 }50 51 @Override //?override52 void makeSound() { //?dogmakesound53 System.out.println(name + " barks: Woof! Woof!");54 }55 // move() is inherited as-is56}5758class Bird extends Animal {59 Bird(String nameTweety) {60 super(name);@Override void makeSound()
19 Bird bird = new Bird("Tweety");20 bird.makeSound(); // Overridden21 bird.move(); // Overridden //?birdmove22 23 System.out.println("\n=== Calling Parent Method with super ===");24 25 Cat cat = new Cat("Whiskers");26 cat.makeSound(); //?supermethod27 }28}2930class Animal {31 String name;32 33 Animal(String name) {34 this.name = name;35 }36 37 void makeSound() { //?parentmakesound38 System.out.println(name + " makes a sound");39 }40 41 void move() {42 System.out.println(name + " moves around");43 }44}4546class Dog extends Animal {47 Dog(String name) {48 super(name);49 }50 51 @Override //?override52 void makeSound() { //?dogmakesound53 System.out.println(name + " barks: Woof! Woof!");54 }55 // move() is inherited as-is56}5758class Bird extends Animal {59 Bird(String name) {60 super(name);61 }62 63 @Override64 void makeSound() {65 System.out.println(nameTweety + " chirps: Tweet! Tweet!");66 }outputTweety chirps: Tweet! Tweet!@Override void move()
20 bird.makeSound(); // Overridden21 bird.move(); // Overridden //?birdmove22 23 System.out.println("\n=== Calling Parent Method with super ===");24 25 Cat cat = new Cat("Whiskers");26 cat.makeSound(); //?supermethod27 }28}2930class Animal {31 String name;32 33 Animal(String name) {34 this.name = name;35 }36 37 void makeSound() { //?parentmakesound38 System.out.println(name + " makes a sound");39 }40 41 void move() {42 System.out.println(name + " moves around");43 }44}4546class Dog extends Animal {47 Dog(String name) {48 super(name);49 }50 51 @Override //?override52 void makeSound() { //?dogmakesound53 System.out.println(name + " barks: Woof! Woof!");54 }55 // move() is inherited as-is56}5758class Bird extends Animal {59 Bird(String name) {60 super(name);61 }62 63 @Override64 void makeSound() {65 System.out.println(name + " chirps: Tweet! Tweet!");66 }67 68 @Override69 void move() { //?birdoverride70 System.out.println(nameTweety + " flies through the air");71 }outputTweety flies through the air === Calling Parent Method with super ===cat ← ⟨Cat D⟩
25 Cat cat→ ⟨Cat D⟩ = new Cat("Whiskers");26 cat.makeSound(); //?supermethod27 }28}2930class Animal {31 String name;32 33 Animal(String name) {34 this.name = name;35 }36 37 void makeSound() { //?parentmakesound38 System.out.println(name + " makes a sound");39 }40 41 void move() {42 System.out.println(name + " moves around");43 }44}4546class Dog extends Animal {47 Dog(String name) {48 super(name);49 }50 51 @Override //?override52 void makeSound() { //?dogmakesound53 System.out.println(name + " barks: Woof! Woof!");54 }55 // move() is inherited as-is56}5758class Bird extends Animal {59 Bird(String name) {60 super(name);61 }62 63 @Override64 void makeSound() {65 System.out.println(name + " chirps: Tweet! Tweet!");66 }67 68 @Override69 void move() { //?birdoverride70 System.out.println(name + " flies through the air");71 }72}7374class Cat extends Animal {75 Cat(String nameWhiskers) {76 super(name);void makeSound()
pass 2 of 237void makeSound() { //?parentmakesound38 System.out.println(nameWhiskers + " makes a sound");39}outputWhiskers makes a soundSystem.out.println(name + " also meows: Meow!");
25 Cat cat = new Cat("Whiskers");26 cat.makeSound(); //?supermethod27 }28}2930class Animal {31 String name;32 33 Animal(String name) {34 this.name = name;35 }36 37 void makeSound() { //?parentmakesound38 System.out.println(name + " makes a sound");39 }40 41 void move() {42 System.out.println(name + " moves around");43 }44}4546class Dog extends Animal {47 Dog(String name) {48 super(name);49 }50 51 @Override //?override52 void makeSound() { //?dogmakesound53 System.out.println(name + " barks: Woof! Woof!");54 }55 // move() is inherited as-is56}5758class Bird extends Animal {59 Bird(String name) {60 super(name);61 }62 63 @Override64 void makeSound() {65 System.out.println(name + " chirps: Tweet! Tweet!");66 }67 68 @Override69 void move() { //?birdoverride70 System.out.println(name + " flies through the air");71 }72}7374class Cat extends Animal {75 Cat(String name) {76 super(name);77 }78 79 @Override80 void makeSound() {81 super.makeSound(); //?superdot82 System.out.println(nameWhiskers + " also meows: Meow!");83 }outputWhiskers also meows: Meow!
Same signature in subclass replaces parent method. Use @Override annotation.
Protected access
Share members with subclasses but not the world.
// Protected Access Modifier
public class Protected {
public static void main(String[] args) {
System.out.println("=== Protected Access ===\n");
// Create BankAccount
BankAccount account = new BankAccount("Alice", 1000);
account.displayInfo();
System.out.println("\n=== SavingsAccount (child) ===");
SavingsAccount savings = new SavingsAccount("Bob", 5000, 0.03);
savings.displayInfo();
savings.addInterest();
savings.displayInfo();
System.out.println("\n=== Access Levels Demo ===");
System.out.println("""
Access Modifiers in Inheritance:
| Modifier | Same Class | Subclass | Other Classes |
|------------|------------|----------|---------------|
| private | Yes | No | No |
| (default) | Yes | Yes* | Yes* |
| protected | Yes | Yes | No |
| public | Yes | Yes | Yes |
* Same package only
""");
}
}
class BankAccount {
private String accountNumber;
protected String ownerName;
protected double balance;
public BankAccount(String owner, double initialBalance) {
this.accountNumber = generateAccountNumber();
this.ownerName = owner;
this.balance = initialBalance;
}
private String generateAccountNumber() {
return "ACC" + System.currentTimeMillis() % 10000;
}
protected void updateBalance(double amount) {
this.balance += amount;
System.out.println("Balance updated by: " + amount);
}
public void displayInfo() {
System.out.println("Account: " + accountNumber);
System.out.println("Owner: " + ownerName);
System.out.println("Balance: $" + balance);
}
}
class SavingsAccount extends BankAccount {
private double interestRate;
public SavingsAccount(String owner, double initialBalance, double rate) {
super(owner, initialBalance);
this.interestRate = rate;
}
public void addInterest() {
// Can access protected field 'balance'
double interest = balance * interestRate;
// Can call protected method
updateBalance(interest);
// Can access protected field 'ownerName'
System.out.println("Interest added for " + ownerName);
// Cannot access private 'accountNumber'!
// System.out.println(accountNumber); // ERROR!
}
}
public static void main(String[] args)
3public class Protected {4 public static void main(String[] args) {5 System.out.println("=== Protected Access ===\n");6 7 // Create BankAccount //?createaccount8 BankAccount account = new BankAccount("Alice", 1000);9 account.displayInfo();output=== Protected Access ===public BankAccount(String owner, double initialBalance)
pass 1 of 240public BankAccount(String ownerAlice, double initialBalance1000.0) {41 this.accountNumber = generateAccountNumber();42 this.ownerName = owner;this.accountNumber ← ACC4895, this.ownerName ← Alice, this.balance ← 1000.0
7 // Create BankAccount //?createaccount8 BankAccount account→ ⟨BankAccount A⟩ = new BankAccount("Alice", 1000);9 account.displayInfo();10 11 System.out.println("\n=== SavingsAccount (child) ===");12 13 SavingsAccount savings = new SavingsAccount("Bob", 5000, 0.03); //?createsavings14 savings.displayInfo();15 savings.addInterest(); //?addinterest16 savings.displayInfo();17 18 System.out.println("\n=== Access Levels Demo ===");19 20 System.out.println("""21 Access Modifiers in Inheritance:22 23 | Modifier | Same Class | Subclass | Other Classes |24 |------------|------------|----------|---------------|25 | private | Yes | No | No |26 | (default) | Yes | Yes* | Yes* |27 | protected | Yes | Yes | No |28 | public | Yes | Yes | Yes |29 30 * Same package only31 """);32 }33}3435class BankAccount {36 private String accountNumber; //?privatefield37 protected String ownerName; //?protectedfield38 protected double balance; //?protectedbalance39 40 public BankAccount(String owner, double initialBalance) {41 this.accountNumber→ ACC4895 = generateAccountNumber();42 this.ownerName→ Alice = ownerAlice;43 this.balance→ 1000.0 = initialBalance1000.0;44 }public void displayInfo()
pass 1 of 38 BankAccount account = new BankAccount("Alice", 1000);9 account.displayInfo();10 11 System.out.println("\n=== SavingsAccount (child) ===");12 13 SavingsAccount savings = new SavingsAccount("Bob", 5000, 0.03); //?createsavings14 savings.displayInfo();15 savings.addInterest(); //?addinterest16 savings.displayInfo();17 18 System.out.println("\n=== Access Levels Demo ===");19 20 System.out.println("""21 Access Modifiers in Inheritance:22 23 | Modifier | Same Class | Subclass | Other Classes |24 |------------|------------|----------|---------------|25 | private | Yes | No | No |26 | (default) | Yes | Yes* | Yes* |27 | protected | Yes | Yes | No |28 | public | Yes | Yes | Yes |29 30 * Same package only31 """);32 }33}3435class BankAccount {36 private String accountNumber; //?privatefield37 protected String ownerName; //?protectedfield38 protected double balance; //?protectedbalance39 40 public BankAccount(String owner, double initialBalance) {41 this.accountNumber = generateAccountNumber();42 this.ownerName = owner;43 this.balance = initialBalance;44 }45 46 private String generateAccountNumber() { //?privatemethod47 return "ACC" + System.currentTimeMillis() % 10000;48 }49 50 protected void updateBalance(double amount) { //?protectedmethod51 this.balance += amount;52 System.out.println("Balance updated by: " + amount);53 }54 55 public void displayInfo() {56 System.out.println("Account: " + accountNumberACC4895);57 System.out.println("Owner: " + ownerNameAlice);58 System.out.println("Balance: $" + balance1000.0);59 }outputAccount: ACC4895 Owner: Alice Balance: $1000.0 === SavingsAccount (child) ===All 3 passes — pass 1 is the card above pass accountNumberownerNamebalanceownerinitialBalanceinterestRateamountinterestthis.balance1 ACC4895 Alice 1000.0 Bob 5000.0 — — — — 2 ACC4899 Bob 5000.0 — — 0.03 150.0 150.0 5000.0 → 5150.0 3 ACC4899 Bob 5150.0 — — — — — — public BankAccount(String owner, double initialBalance)
pass 2 of 240public BankAccount(String ownerBob, double initialBalance5000.0) {41 this.accountNumber = generateAccountNumber();42 this.ownerName = owner;this.accountNumber ← ACC4899, this.ownerName ← Bob, this.balance ← 5000.0
40public BankAccount(String owner, double initialBalance) {41 this.accountNumber→ ACC4899 = generateAccountNumber();42 this.ownerName→ Bob = ownerBob;43 this.balance→ 5000.0 = initialBalance5000.0;44}this.interestRate ← 0.03, savings ← ⟨SavingsAccount B⟩
13 SavingsAccount savings→ ⟨SavingsAccount B⟩ = new SavingsAccount("Bob", 5000, 0.03); //?createsavings14 savings.displayInfo();15 savings.addInterest(); //?addinterest16 savings.displayInfo();17 18 System.out.println("\n=== Access Levels Demo ===");19 20 System.out.println("""21 Access Modifiers in Inheritance:22 23 | Modifier | Same Class | Subclass | Other Classes |24 |------------|------------|----------|---------------|25 | private | Yes | No | No |26 | (default) | Yes | Yes* | Yes* |27 | protected | Yes | Yes | No |28 | public | Yes | Yes | Yes |29 30 * Same package only31 """);32 }33}3435class BankAccount {36 private String accountNumber; //?privatefield37 protected String ownerName; //?protectedfield38 protected double balance; //?protectedbalance39 40 public BankAccount(String owner, double initialBalance) {41 this.accountNumber = generateAccountNumber();42 this.ownerName = owner;43 this.balance = initialBalance;44 }45 46 private String generateAccountNumber() { //?privatemethod47 return "ACC" + System.currentTimeMillis() % 10000;48 }49 50 protected void updateBalance(double amount) { //?protectedmethod51 this.balance += amount;52 System.out.println("Balance updated by: " + amount);53 }54 55 public void displayInfo() {56 System.out.println("Account: " + accountNumber);57 System.out.println("Owner: " + ownerName);58 System.out.println("Balance: $" + balance);59 }60}6162class SavingsAccount extends BankAccount {63 private double interestRate;64 65 public SavingsAccount(String ownerBob, double initialBalance5000.0, double rate0.03) {66 super(owner, initialBalance);67 this.interestRate→ 0.03 = rate0.03;68 }interest ← 150.0
70public void addInterest() {71 // Can access protected field 'balance' //?accessprotected72 double interest→ 150.0 = balance5000.0 * interestRate0.03;73 74 // Can call protected method //?callprotected75 updateBalance(interest150.0);this.balance ← 5150.0
50protected void updateBalance(double amount150.0) { //?protectedmethod51 this.balance→ 5150.0 += amount150.0;52 System.out.println("Balance updated by: " + amount150.0);53}outputBalance updated by: 150.0updateBalance(interest);
14 savings.displayInfo();15 savings.addInterest(); //?addinterest16 savings.displayInfo();17 18 System.out.println("\n=== Access Levels Demo ===");19 20 System.out.println("""21 Access Modifiers in Inheritance:22 23 | Modifier | Same Class | Subclass | Other Classes |24 |------------|------------|----------|---------------|25 | private | Yes | No | No |26 | (default) | Yes | Yes* | Yes* |27 | protected | Yes | Yes | No |28 | public | Yes | Yes | Yes |29 30 * Same package only31 """);32 }33}3435class BankAccount {36 private String accountNumber; //?privatefield37 protected String ownerName; //?protectedfield38 protected double balance; //?protectedbalance39 40 public BankAccount(String owner, double initialBalance) {41 this.accountNumber = generateAccountNumber();42 this.ownerName = owner;43 this.balance = initialBalance;44 }45 46 private String generateAccountNumber() { //?privatemethod47 return "ACC" + System.currentTimeMillis() % 10000;48 }49 50 protected void updateBalance(double amount) { //?protectedmethod51 this.balance += amount;52 System.out.println("Balance updated by: " + amount);53 }54 55 public void displayInfo() {56 System.out.println("Account: " + accountNumber);57 System.out.println("Owner: " + ownerName);58 System.out.println("Balance: $" + balance);59 }60}6162class SavingsAccount extends BankAccount {63 private double interestRate;64 65 public SavingsAccount(String owner, double initialBalance, double rate) {66 super(owner, initialBalance);67 this.interestRate = rate;68 }69 70 public void addInterest() {71 // Can access protected field 'balance' //?accessprotected72 double interest = balance * interestRate;73 74 // Can call protected method //?callprotected75 updateBalance(interest150.0);76 77 // Can access protected field 'ownerName'78 System.out.println("Interest added for " + ownerNameBob);outputInterest added for Bob
protected is visible in subclasses and same package. More open than private.
Multi-level inheritance
Chain of inheritance: grandparent → parent → child.
// Multi-Level Inheritance Chain
public class InheritanceChain {
public static void main(String[] args) {
System.out.println("=== Multi-Level Inheritance ===\n");
// Create SportsCar (3 levels deep)
SportsCar ferrari = new SportsCar("Ferrari", "488", 2023, 660);
ferrari.displayInfo();
System.out.println("\n--- Demonstrating Methods ---");
ferrari.start(); // From Vehicle
ferrari.accelerate(); // From Car
ferrari.boost(); // From SportsCar
ferrari.stop(); // From Vehicle
System.out.println("\n=== Inheritance Hierarchy ===");
System.out.println("""
Vehicle (grandparent)
↓
Car (parent)
↓
SportsCar (child)
SportsCar inherits from Car,
which inherits from Vehicle.
SportsCar has access to ALL
non-private members of both!
""");
System.out.println("=== Creating Different Levels ===\n");
Vehicle vehicle = new Vehicle("Generic");
vehicle.displayInfo();
vehicle.start();
System.out.println();
Car car = new Car("Toyota", "Camry", 2022);
car.displayInfo();
car.start();
car.accelerate();
}
}
// Level 1: Base class
class Vehicle {
protected String brand;
Vehicle(String brand) {
this.brand = brand;
}
void start() {
System.out.println(brand + ": Starting engine...");
}
void stop() {
System.out.println(brand + ": Stopping...");
}
void displayInfo() {
System.out.println("Brand: " + brand);
}
}
// Level 2: Extends Vehicle
class Car extends Vehicle {
protected String model;
protected int year;
Car(String brand, String model, int year) {
super(brand);
this.model = model;
this.year = year;
}
void accelerate() {
System.out.println(brand + " " + model + ": Accelerating...");
}
@Override
void displayInfo() {
super.displayInfo();
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}
// Level 3: Extends Car
class SportsCar extends Car {
private int horsepower;
SportsCar(String brand, String model, int year, int hp) {
super(brand, model, year);
this.horsepower = hp;
}
void boost() {
System.out.println(brand + " " + model + ": BOOST! (+" + horsepower + " HP)");
}
@Override
void displayInfo() {
super.displayInfo(); // Calls Car's displayInfo
System.out.println("Horsepower: " + horsepower);
}
}
public static void main(String[] args)
3public class InheritanceChain {4 public static void main(String[] args) {5 System.out.println("=== Multi-Level Inheritance ===\n");6 7 // Create SportsCar (3 levels deep) //?createsports8 SportsCar ferrari = new SportsCar("Ferrari", "488", 2023, 660);9 ferrari.displayInfo();output=== Multi-Level Inheritance ===this.brand ← Ferrari
pass 1 of 352Vehicle(String brandFerrari) {53 this.brand→ Ferrari = brandFerrari;54}All 3 passes — pass 1 is the card above pass brandmodelyearhpthis.brandthis.modelthis.yearthis.horsepowerferrarivehiclecar1 Ferrari 488 2023 660 Ferrari 488 2023 660 ⟨SportsCar A⟩ — — 2 Generic — — — Generic — — — — ⟨Vehicle B⟩ — 3 Toyota Camry 2022 — Toyota Camry 2022 — — — ⟨Car C⟩ this.model ← 488, this.year ← 2023
pass 1 of 274Car(String brandFerrari, String model488, int year2023) {75 super(brand); //?superlevel276 this.model→ 488 = model488;77 this.year→ 2023 = year2023;78}this.horsepower ← 660, ferrari ← ⟨SportsCar A⟩
7 // Create SportsCar (3 levels deep) //?createsports8 SportsCar ferrari→ ⟨SportsCar A⟩ = new SportsCar("Ferrari", "488", 2023, 660);9 ferrari.displayInfo();10 11 System.out.println("\n--- Demonstrating Methods ---");12 ferrari.start(); // From Vehicle13 ferrari.accelerate(); // From Car14 ferrari.boost(); // From SportsCar //?boostcall15 ferrari.stop(); // From Vehicle16 17 System.out.println("\n=== Inheritance Hierarchy ===");18 System.out.println("""19 20 Vehicle (grandparent)21 ↓22 Car (parent)23 ↓24 SportsCar (child)25 26 SportsCar inherits from Car,27 which inherits from Vehicle.28 29 SportsCar has access to ALL30 non-private members of both!31 """);32 33 System.out.println("=== Creating Different Levels ===\n");34 35 Vehicle vehicle = new Vehicle("Generic"); //?createvehicle36 vehicle.displayInfo();37 vehicle.start();38 39 System.out.println();40 41 Car car = new Car("Toyota", "Camry", 2022); //?createcar42 car.displayInfo();43 car.start();44 car.accelerate();45 }46}4748// Level 1: Base class //?level149class Vehicle {50 protected String brand;51 52 Vehicle(String brand) {53 this.brand = brand;54 }55 56 void start() {57 System.out.println(brand + ": Starting engine...");58 }59 60 void stop() {61 System.out.println(brand + ": Stopping...");62 }63 64 void displayInfo() {65 System.out.println("Brand: " + brand);66 }67}6869// Level 2: Extends Vehicle //?level270class Car extends Vehicle {71 protected String model;72 protected int year;73 74 Car(String brand, String model, int year) {75 super(brand); //?superlevel276 this.model = model;77 this.year = year;78 }79 80 void accelerate() {81 System.out.println(brand + " " + model + ": Accelerating...");82 }83 84 @Override85 void displayInfo() {86 super.displayInfo(); //?superdisplay87 System.out.println("Model: " + model);88 System.out.println("Year: " + year);89 }90}9192// Level 3: Extends Car //?level393class SportsCar extends Car {94 private int horsepower;95 96 SportsCar(String brandFerrari, String model488, int year2023, int hp660) {97 super(brand, model, year); //?superlevel398 this.horsepower→ 660 = hp660;99 }void displayInfo()
pass 1 of 364void displayInfo() {65 System.out.println("Brand: " + brandFerrari);66}outputBrand: FerrariAll 3 passes — pass 1 is the card above pass brandmodelyearthis.modelthis.yearcar1 Ferrari — — — — — 2 Generic Camry 2022 Camry 2022 ⟨Car C⟩ 3 Toyota — — — — — System.out.println("Model: " + model);
85void displayInfo() {86 super.displayInfo(); //?superdisplay87 System.out.println("Model: " + model488);88 System.out.println("Year: " + year2023);89}outputModel: 488 Year: 2023System.out.println("Horsepower: " + horsepower);
8 SportsCar ferrari = new SportsCar("Ferrari", "488", 2023, 660);9 ferrari.displayInfo();10 11 System.out.println("\n--- Demonstrating Methods ---");12 ferrari.start(); // From Vehicle13 ferrari.accelerate(); // From Car14 ferrari.boost(); // From SportsCar //?boostcall15 ferrari.stop(); // From Vehicle16 17 System.out.println("\n=== Inheritance Hierarchy ===");18 System.out.println("""19 20 Vehicle (grandparent)21 ↓22 Car (parent)23 ↓24 SportsCar (child)25 26 SportsCar inherits from Car,27 which inherits from Vehicle.28 29 SportsCar has access to ALL30 non-private members of both!31 """);32 33 System.out.println("=== Creating Different Levels ===\n");34 35 Vehicle vehicle = new Vehicle("Generic"); //?createvehicle36 vehicle.displayInfo();37 vehicle.start();38 39 System.out.println();40 41 Car car = new Car("Toyota", "Camry", 2022); //?createcar42 car.displayInfo();43 car.start();44 car.accelerate();45 }46}4748// Level 1: Base class //?level149class Vehicle {50 protected String brand;51 52 Vehicle(String brand) {53 this.brand = brand;54 }55 56 void start() {57 System.out.println(brand + ": Starting engine...");58 }59 60 void stop() {61 System.out.println(brand + ": Stopping...");62 }63 64 void displayInfo() {65 System.out.println("Brand: " + brand);66 }67}6869// Level 2: Extends Vehicle //?level270class Car extends Vehicle {71 protected String model;72 protected int year;73 74 Car(String brand, String model, int year) {75 super(brand); //?superlevel276 this.model = model;77 this.year = year;78 }79 80 void accelerate() {81 System.out.println(brand + " " + model + ": Accelerating...");82 }83 84 @Override85 void displayInfo() {86 super.displayInfo(); //?superdisplay87 System.out.println("Model: " + model);88 System.out.println("Year: " + year);89 }90}9192// Level 3: Extends Car //?level393class SportsCar extends Car {94 private int horsepower;95 96 SportsCar(String brand, String model, int year, int hp) {97 super(brand, model, year); //?superlevel398 this.horsepower = hp;99 }100 101 void boost() { //?boostmethod102 System.out.println(brand + " " + model + ": BOOST! (+" + horsepower + " HP)");103 }104 105 @Override106 void displayInfo() {107 super.displayInfo(); // Calls Car's displayInfo //?superchain108 System.out.println("Horsepower: " + horsepower660);109 }outputHorsepower: 660 --- Demonstrating Methods ---void start()
pass 1 of 311 System.out.println("\n--- Demonstrating Methods ---");12 ferrari.start(); // From Vehicle13 ferrari.accelerate(); // From Car14 ferrari.boost(); // From SportsCar //?boostcall15 ferrari.stop(); // From Vehicle16 17 System.out.println("\n=== Inheritance Hierarchy ===");18 System.out.println("""19 20 Vehicle (grandparent)21 ↓22 Car (parent)23 ↓24 SportsCar (child)25 26 SportsCar inherits from Car,27 which inherits from Vehicle.28 29 SportsCar has access to ALL30 non-private members of both!31 """);32 33 System.out.println("=== Creating Different Levels ===\n");34 35 Vehicle vehicle = new Vehicle("Generic"); //?createvehicle36 vehicle.displayInfo();37 vehicle.start();38 39 System.out.println();40 41 Car car = new Car("Toyota", "Camry", 2022); //?createcar42 car.displayInfo();43 car.start();44 car.accelerate();45 }46}4748// Level 1: Base class //?level149class Vehicle {50 protected String brand;51 52 Vehicle(String brand) {53 this.brand = brand;54 }55 56 void start() {57 System.out.println(brandFerrari + ": Starting engine...");58 }outputFerrari: Starting engine...All 3 passes — pass 1 is the card above pass brandmodelhorsepoweryearthis.modelthis.yearcar1 Ferrari 488 660 — — — — 2 Generic Camry — 2022 Camry 2022 ⟨Car C⟩ 3 Toyota Camry — — — — — void accelerate()
pass 1 of 212 ferrari.start(); // From Vehicle13 ferrari.accelerate(); // From Car14 ferrari.boost(); // From SportsCar //?boostcall15 ferrari.stop(); // From Vehicle16 17 System.out.println("\n=== Inheritance Hierarchy ===");18 System.out.println("""19 20 Vehicle (grandparent)21 ↓22 Car (parent)23 ↓24 SportsCar (child)25 26 SportsCar inherits from Car,27 which inherits from Vehicle.28 29 SportsCar has access to ALL30 non-private members of both!31 """);32 33 System.out.println("=== Creating Different Levels ===\n");34 35 Vehicle vehicle = new Vehicle("Generic"); //?createvehicle36 vehicle.displayInfo();37 vehicle.start();38 39 System.out.println();40 41 Car car = new Car("Toyota", "Camry", 2022); //?createcar42 car.displayInfo();43 car.start();44 car.accelerate();45 }46}4748// Level 1: Base class //?level149class Vehicle {50 protected String brand;51 52 Vehicle(String brand) {53 this.brand = brand;54 }55 56 void start() {57 System.out.println(brand + ": Starting engine...");58 }59 60 void stop() {61 System.out.println(brand + ": Stopping...");62 }63 64 void displayInfo() {65 System.out.println("Brand: " + brand);66 }67}6869// Level 2: Extends Vehicle //?level270class Car extends Vehicle {71 protected String model;72 protected int year;73 74 Car(String brand, String model, int year) {75 super(brand); //?superlevel276 this.model = model;77 this.year = year;78 }79 80 void accelerate() {81 System.out.println(brandFerrari + " " + model488 + ": Accelerating...");82 }outputFerrari 488: Accelerating...void boost()
13 ferrari.accelerate(); // From Car14 ferrari.boost(); // From SportsCar //?boostcall15 ferrari.stop(); // From Vehicle16 17 System.out.println("\n=== Inheritance Hierarchy ===");18 System.out.println("""19 20 Vehicle (grandparent)21 ↓22 Car (parent)23 ↓24 SportsCar (child)25 26 SportsCar inherits from Car,27 which inherits from Vehicle.28 29 SportsCar has access to ALL30 non-private members of both!31 """);32 33 System.out.println("=== Creating Different Levels ===\n");34 35 Vehicle vehicle = new Vehicle("Generic"); //?createvehicle36 vehicle.displayInfo();37 vehicle.start();38 39 System.out.println();40 41 Car car = new Car("Toyota", "Camry", 2022); //?createcar42 car.displayInfo();43 car.start();44 car.accelerate();45 }46}4748// Level 1: Base class //?level149class Vehicle {50 protected String brand;51 52 Vehicle(String brand) {53 this.brand = brand;54 }55 56 void start() {57 System.out.println(brand + ": Starting engine...");58 }59 60 void stop() {61 System.out.println(brand + ": Stopping...");62 }63 64 void displayInfo() {65 System.out.println("Brand: " + brand);66 }67}6869// Level 2: Extends Vehicle //?level270class Car extends Vehicle {71 protected String model;72 protected int year;73 74 Car(String brand, String model, int year) {75 super(brand); //?superlevel276 this.model = model;77 this.year = year;78 }79 80 void accelerate() {81 System.out.println(brand + " " + model + ": Accelerating...");82 }83 84 @Override85 void displayInfo() {86 super.displayInfo(); //?superdisplay87 System.out.println("Model: " + model);88 System.out.println("Year: " + year);89 }90}9192// Level 3: Extends Car //?level393class SportsCar extends Car {94 private int horsepower;95 96 SportsCar(String brand, String model, int year, int hp) {97 super(brand, model, year); //?superlevel398 this.horsepower = hp;99 }100 101 void boost() { //?boostmethod102 System.out.println(brandFerrari + " " + model488 + ": BOOST! (+" + horsepower660 + " HP)");103 }outputFerrari 488: BOOST! (+660 HP)void stop()
14 ferrari.boost(); // From SportsCar //?boostcall15 ferrari.stop(); // From Vehicle16 17 System.out.println("\n=== Inheritance Hierarchy ===");18 System.out.println("""19 20 Vehicle (grandparent)21 ↓22 Car (parent)23 ↓24 SportsCar (child)25 26 SportsCar inherits from Car,27 which inherits from Vehicle.28 29 SportsCar has access to ALL30 non-private members of both!31 """);32 33 System.out.println("=== Creating Different Levels ===\n");34 35 Vehicle vehicle = new Vehicle("Generic"); //?createvehicle36 vehicle.displayInfo();37 vehicle.start();38 39 System.out.println();40 41 Car car = new Car("Toyota", "Camry", 2022); //?createcar42 car.displayInfo();43 car.start();44 car.accelerate();45 }46}4748// Level 1: Base class //?level149class Vehicle {50 protected String brand;51 52 Vehicle(String brand) {53 this.brand = brand;54 }55 56 void start() {57 System.out.println(brand + ": Starting engine...");58 }59 60 void stop() {61 System.out.println(brandFerrari + ": Stopping...");62 }outputFerrari: Stopping... === Inheritance Hierarchy === Vehicle (grandparent) ↓ Car (parent) ↓ SportsCar (child) SportsCar inherits from Car, which inherits from Vehicle. SportsCar has access to ALL non-private members of both! === Creating Different Levels ===this.model ← Camry, this.year ← 2022, car ← ⟨Car C⟩
pass 2 of 241 Car car→ ⟨Car C⟩ = new Car("Toyota", "Camry", 2022); //?createcar42 car.displayInfo();43 car.start();44 car.accelerate();45 }46}4748// Level 1: Base class //?level149class Vehicle {50 protected String brand;51 52 Vehicle(String brand) {53 this.brand = brand;54 }55 56 void start() {57 System.out.println(brand + ": Starting engine...");58 }59 60 void stop() {61 System.out.println(brand + ": Stopping...");62 }63 64 void displayInfo() {65 System.out.println("Brand: " + brand);66 }67}6869// Level 2: Extends Vehicle //?level270class Car extends Vehicle {71 protected String model;72 protected int year;73 74 Car(String brandToyota, String modelCamry, int year2022) {75 super(brand); //?superlevel276 this.model→ Camry = modelCamry;77 this.year→ 2022 = year2022;78 }System.out.println("Model: " + model);
41 Car car = new Car("Toyota", "Camry", 2022); //?createcar42 car.displayInfo();43 car.start();44 car.accelerate();45 }46}4748// Level 1: Base class //?level149class Vehicle {50 protected String brand;51 52 Vehicle(String brand) {53 this.brand = brand;54 }55 56 void start() {57 System.out.println(brand + ": Starting engine...");58 }59 60 void stop() {61 System.out.println(brand + ": Stopping...");62 }63 64 void displayInfo() {65 System.out.println("Brand: " + brand);66 }67}6869// Level 2: Extends Vehicle //?level270class Car extends Vehicle {71 protected String model;72 protected int year;73 74 Car(String brand, String model, int year) {75 super(brand); //?superlevel276 this.model = model;77 this.year = year;78 }79 80 void accelerate() {81 System.out.println(brand + " " + model + ": Accelerating...");82 }83 84 @Override85 void displayInfo() {86 super.displayInfo(); //?superdisplay87 System.out.println("Model: " + modelCamry);88 System.out.println("Year: " + year2022);89 }outputModel: Camry Year: 2022void accelerate()
pass 2 of 243 car.start();44 car.accelerate();45 }46}4748// Level 1: Base class //?level149class Vehicle {50 protected String brand;51 52 Vehicle(String brand) {53 this.brand = brand;54 }55 56 void start() {57 System.out.println(brand + ": Starting engine...");58 }59 60 void stop() {61 System.out.println(brand + ": Stopping...");62 }63 64 void displayInfo() {65 System.out.println("Brand: " + brand);66 }67}6869// Level 2: Extends Vehicle //?level270class Car extends Vehicle {71 protected String model;72 protected int year;73 74 Car(String brand, String model, int year) {75 super(brand); //?superlevel276 this.model = model;77 this.year = year;78 }79 80 void accelerate() {81 System.out.println(brandToyota + " " + modelCamry + ": Accelerating...");82 }outputToyota Camry: Accelerating...
Child inherits from parent, which inherits from grandparent. Chain can be long.
Exercise: Practical.java
Build a complete class hierarchy with inheritance