Introduction to Inheritance | 9.1/9.2 | 9.3/9.4 | 9.5 | 9.6 | 9.7 |
9.3/9.4 Introduction
Team Teach for Java.
Method Overrides
Every class inherits methods from its parent class. These methods can be called in the child class and can also be overridden.
public class Shape {
protected String name;
private int length;
private int width;
// Default constructor
public Shape() {
this.name = "rectangle";
this.length = 10;
this.width = 5;
}
// Parameterized constructor
public Shape(String name, int length, int width) {
this.name = name;
this.length = length;
this.width = width;
}
// Getter methods
public String get_name() {
return this.name;
}
public int get_length() {
return this.length;
}
public int get_width() {
return this.width;
}
// Setter methods
public void set_name(String n) {
this.name = n;
}
public void set_length(int a) {
this.length = a;
}
public void set_width(int b) {
this.width = b;
}
// Method to calculate the area
public double calc_area() {
return this.length * this.width;
}
// Method to print the shape
public void print_shape() {
System.out.println("Shape: " + this.name);
}
// Additional method to print something
public void print_something() {
System.out.println("This is a shape");
}
}
public class Driver {
public static void main(String[] args) {
Shape s1 = new Shape();
}
}
// Run the driver code
Driver.main(new String[0]);
Creating a Triangle:
Currently Our shape class only takes in length and width parameters. This works fine for squares and rectangles, but what if we wanted to make a different shape? To define a Triangle we can use the 3 side lengths. while still inheriting the same behavior from the base Shape class.
public class Triangle extends Shape {
private int side1;
private int side2;
private int side3;
public Triangle() {
this.name = "triangle";
this.side1 = 1;
this.side2 = 2;
this.side3 = 3;
}
// Constructor that takes a name and three side lengths
public Triangle(String name, int s1, int s2, int s3) {
super(name, 0, 0); // Call to Shape constructor to set the name
this.name = "triangle";
this.side1 = s1;
this.side2 = s2;
this.side3 = s3;
}
@Override
public double calc_area() {
double s = (side1 + side2 + side3) / 2.0; // Semi-perimeter
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
@Override
public void print_something() {
System.out.println("This is a Triangle");
}
}
public class Driver {
public static void main(String[] args) {
Triangle t1 = new Triangle("triangle", 3, 3, 3);
System.out.println("Area of t1 = " + t1.calc_area());
}
}
// Run the driver code
Driver.main(new String[0]);
Area of t1 = 3.897114317029974
Here’s our Triangle
As seen above, we’re creating a new child class: Triangle This class inherits name paramiter from the parent shape class and takes in 3 new side length paramiters to define the triangle’s geometry.