How to use inheritance in java programming tutorial


In this lesson, you'll learn how to use inheritance to define classes that extend other classes. Check out the program Rectangle class has fields width and height and a constructor in the main method a new object is created and its area is printed.

public class Main{
public static void main(){
Rectangle rect = new Rectangle(100,200);
Square square = new Square(100);  // new square object
System.out.println(square.getArea());
System.out.println(rect.getArea());
}
}
class Square extends Rectangle //new class square added
{
public Square (int size){
super(size,size); //constructor added
}
}

}
class Rectangle{
private int width;
private int height;
public Rectangle(int width, int height)
{
this.width= width;
this.height=height;
}
public int getArea(){
return width*height;
}
}

as you can see it printed the product of "width*height" which is 20000. Now try to add on your own a new class "square{}" above the Rectangle class write extends Rectangle behind the class name square, to make the square class extends the Rectangle class. Normally you'll get an error message that says that we have to provide a constructor for the Square class. We have added a constructor that takes just a size look at the code above. we call the "super" constructor, which is the constructor of the Rectangle class and pass the "size" as width and height. in the main method we create a new Square Object, pass "size" 100 to the new constructor, and assign it to a new variable (Square square), we call square.getArea() to get the area of the Square and print it. The getArea() method is inherited by the Square class from the Rectangle class. Now we can also change the type of the variable to Rectangle. Even though the actual object is a Square you can use the type of the inherited class is called Polymorphous.

Post a Comment

0 Comments