Java Subclass and Inheritance
Java Subclass and Inheritance
- Every class, that extends another class will inherits the capabilities of that class.
- Any class that does not explicitly state which class it extends, will extends automatically the class java.lang.Object existing in the Java library.
- The class, java.lang.Object, provides the basic operations and actions that every class need.
- A class that inherits the features from another class is a sub-class to the class it inherits from.
- Any class that is inherited is called the super-class to the classes that inherit from the class.
- Remember that a class with final modifier in front can not be sub-classed.
- Inheritance is the second of the three main OOP concepts and plays an important role in this context.
Class and sub-class example:
// Rectangle is super class to Square // Rectangle is sub-class to java.lang.Object class Rectangle { private final int width; private final int height; public int getWidth() { return width; } public int getHeight() { return height; } public int getArea() { return width * height; } public Rectangle(int width, int height) { this.width = width; this.height = height; } @Override public String toString() { return "This " + this.getClass().getSimpleName() + " has an area of " + getArea(); } } // Square is sub-class to Rectangle class Square extends Rectangle { public Square(int width) { super(width, width); } @Override public String toString() { return super.toString(); } } public class SubClassing { public static void main(String args[]) { Rectangle rectangle = new Rectangle(34, 56); System.out.println(rectangle); Square square = new Square(44); System.out.println(square); } }
The result of this is:This Rectangle has an area of 1904 This Square has an area of 1936
© 2010 by Finnesand Data.
All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the
correctness in the pages or source codes.
The risk of using this web-site pages or any program
codes from this website is entirely at the individual user.