Master Object-Oriented Programming with classes, inheritance, and ArrayList collections.
Build real-world applications using OOP principles and dynamic data structures.
Person class that encapsulates personal data with private fields, a constructor, getters/setters, and a display method.private String name;private int age;public Person(String name, int age) { this.name = name; this.age = age; }getName(), setName(String name)getAge(), setAge(int age)Person: Alice, Age: 25
Person: Bob, Age: 30
After birthday: Bob, Age: 31
private String name;public Person(String name, int age) { this.name = name; }public String getName() { return name; }public void setAge(int age) { this.age = age; }Review feedback below
Animal class and derived Dog and Cat classes that override methods.protected String name; (accessible by subclasses)makeSound() method printing generic soundsuper(name)@Override makeSound() to print "Woof!"super(name)@Override makeSound() to print "Meow!"extends - inherits from parent classsuper() - calls parent constructor@Override - indicates method overridingprotected - accessible in subclassesBuddy says: Woof!
Whiskers says: Meow!
-- Polymorphism Demo --
Woof!
Meow!
class Dog extends Animal { }super(name);@Override public void makeSound() { }Animal a = new Dog("Rex");Review feedback below
import java.util.ArrayList;ArrayList<String> students = new ArrayList<>();add() method - add at least 4 names.for (String student : students) { ... }remove() method.contains() method.size() method.All students:
- Alice
- Bob
- Charlie
- Diana
Total: 4 students
After removing Bob:
- Alice
- Charlie
- Diana
Contains Alice? true
Contains Bob? false
import java.util.ArrayList;ArrayList<String> list = new ArrayList<>();list.add("item");for (String s : list) { }list.size() - Contains: list.contains("x")Review feedback below