[Tutorial] Java Inheritance Introduction
Submit solution
Java
Points:
10
Time limit:
1.0s
Memory limit:
2M
Author:
Problem type
Allowed languages
Inheritance
Inheritance is the mechanism of basing an object or class upon another object or class, retaining similar implementation.
superclass (parent) - the class being inherited from subclass (child) - the class that inherits from another class
Example
/*
* Created: Ramaguru Radhakrishnan
* Date: 08-May-2023
*
*/
class Shape {
// Method (does not have a body)
public void area() { }
// Method
public void display() {
System.out.println("[Super] Calculating Area");
}
}
// Subclass (inherited from Shape)
class Circle extends Shape {
public void area() {
// area() of Circle Class - Definition
System.out.println("[Circle] Area of Circle is PI*R*R");
}
}
// Subclass (inherited from Shape)
class Rectangle extends Shape {
public void area() {
// area() of Rectangle Class - Definition
System.out.println("[Rectangle] Area of Rectangle is L*B");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("[Main] Creating Objects Circle and Rectangle");
Circle myCircle = new Circle(); // Create a Circle object
myCircle.display();
myCircle.area();
Rectangle myRect = new Rectangle(); // Create a Rectangle object
myRect.display();
myRect.area();
}
}
Comments