Extending Classes
Inheritance allows a class to inherit properties and methods from another class. Use the extends keyword.
Example
// Parent class
public class Animal {
protected String name;
protected int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public void eat() {
System.out.println(name + " is eating.");
}
public String toString() {
return name + " (age: " + age + ")";
}
}
// Child class
public class Dog extends Animal {
private String breed;
public Dog(String name, int age, String breed) {
super(name, age); // call parent constructor
this.breed = breed;
}
public void bark() {
System.out.println(name + " says Woof!");
}
}
Dog dog = new Dog("Rex", 3, "Labrador");
dog.eat(); // inherited
dog.bark(); // own method Method Overriding
A child class can override a parent method to provide its own implementation.
Example
public class Shape {
public double area() {
return 0;
}
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
public class Rectangle extends Shape {
private double width, height;
public Rectangle(double w, double h) {
this.width = w;
this.height = h;
}
@Override
public double area() {
return width * height;
}
} 