Wednesday 19 February 2014

Inheritance

Inheritance is the concept of re usability. Object of one class can get the properties and methods of object of another class by using inheritance. One class can use the methods and properties of other class.

When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class.

A class that is derived from another class is called a subclass. The class from which the subclass is derived is called a super class. Sub class inherits the properties and methods of super class using the extends keyword.

By default all classes extends the Object class, which is the super class for all classes in Java.

   class SuperClass{

   }

   class SubClass extends SuperClass{

   }

i.e, subclass adding the extra functionality to the super class.

Example

Rectangle
area = width x height
perimeter = 2 * (width + height)

Square
area = s * s
perimeter = 4s

where s is the length of side

class Rectangle{
 double width, height;
 
 Rectangle(){
  width = height = 0;
 }

 Rectangle(double width, double height){
  this.width = width;
  this.height = height;
 }

 Rectangle(double width){
  this.width = this.height = width;
 }

 double getArea(){
  return (width * height);
 }

 double getPerimeter(){
  return (2 * (width + height));
 }
}


class Square extends Rectangle{
 Square(double s){
  width = height = s;
 }

 double getSquarePerimeter(){
  return (4*width);
 }

 public static void main(String args[]){
  Square s1 = new Square(10);
  System.out.println(s1.getArea());
  System.out.println(s1.getSquarePerimeter());
 }
}
 
Output
100.0
40.0

As you see in the above, Square class don't have fields like width, height, still it can access the width and height, since, Square extending the class Rectangle. In the same way Square object calls the method getArea() of Rectangle class.

Some points to remember
1. Object class is the super class for all the classes

2. Sub classes can access the all the data and methods of super classes, other than private fields and private methods



Default methods vs Multiple Inheritance                                                 Types Of Inheritance                                                 Home

No comments:

Post a Comment