Explore advanced object-oriented programming concepts and best practices.
Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and methods from another class. Polymorphism enables objects to be treated as instances of their parent class while maintaining their unique implementations.
// Superclass
public class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void makeSound() {
System.out.println("Some generic sound");
}
}
// Subclass
public class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name); // Call to superclass constructor
this.breed = breed;
}
@Override
public void makeSound() {
System.out.println("Woof!");
}
// Call superclass version of overridden method
public void makeAnimalSound() {
super.makeSound();
}
}
// Polymorphic usage
Animal myPet = new Dog("Rex", "German Shepherd");
myPet.makeSound(); // Outputs: "Woof!"
public abstract class Shape {
public abstract double area();
public abstract double perimeter();
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
@Override
public double perimeter() {
return 2 * Math.PI * radius;
}
}