[go: up one dir, main page]

0% found this document useful (0 votes)
75 views9 pages

Lecture 8 Inheritance, Polymophism and Interfaces

Inheritance allows a class to acquire properties of another class. A subclass inherits variables and methods from its superclass. The subclass can use or override inherited members. Inheritance provides benefits like code reuse, cleaner design, and modeling "is-a" relationships. Polymorphism allows determining at runtime which code to run based on an object's type through method overriding. Abstract classes cannot be instantiated but provide a common interface for subclasses to implement through abstract methods.

Uploaded by

Rozzelly
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views9 pages

Lecture 8 Inheritance, Polymophism and Interfaces

Inheritance allows a class to acquire properties of another class. A subclass inherits variables and methods from its superclass. The subclass can use or override inherited members. Inheritance provides benefits like code reuse, cleaner design, and modeling "is-a" relationships. Polymorphism allows determining at runtime which code to run based on an object's type through method overriding. Abstract classes cannot be instantiated but provide a common interface for subclasses to implement through abstract methods.

Uploaded by

Rozzelly
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

INHERITANCE

Inheritance is the ability of a class to acquire properties of another class. A subclass inherits variables and
methods from its superclass. The subclass can use these members as they are, or it can hide the member
variables or override the methods. Defining a new class based on an existing class is called derivation
The original class is called a base class because it forms the base for the definition of the derived class. It is
also referred to as super class of the derived class
The derived class is usually called sub or derived class i.e. more specialized version of the base class and is used
to model the “is-a” relationship
Creating a subclass can be as simple as including the extends clause in your class declaration. However, you
usually have to make other provisions in your code when subclassing a class, such as overriding methods or
providing implementations for abstract methods.

Syntax
public class <name> extends <superclass name> {}

Example
public class Employee {
//members of the Employee class
}
public class Manager extends Employee {
//members of the Manager class
}

The extends keyword identifies that Employee is a base class for Manager and so an object of type Manager
will have members that are inherited from the Employee class in addition to members of the Manager class that
appears in its definition.

Note:
1. Constructors are not members and are not inherited by subclasses.
2. A subclass is a class that extends another class. It inherits state and behavior from all of its ancestors.
3. The term "superclass" refers to a class's direct ancestor as well as to all of its ascendant classes
(multilevel inheritance).

Importance of inheritance
i). Clean up program design
ii). Save on coding
iii). Make it easier to allow for future extensions
iv). Re-use current classes (Avoid re-inventing the wheel)
v). Capture complex behaviors

Example of Inheritance

UML Representation

Superclass Subclass

Circle Cylinder
-radius
-length
+getRadius
+setRadius +getLength
+findArea +setLength
+findVolume
1
The program

import java.util.Scanner;
class Circle{
protected double radius;
void setRadius(double r) {
radius = r;
}
public double getRadius() {
return radius;
}
public double findArea (){
return Math.PI*Math.pow(radius,2);
}
}
class Cylinder extends Circle{
private double length;
void setLength(double l) {
length = l;
}
public double getLength() {
return length;
}
public double findVolume (){
return findArea()*length;
}
}
public class Compute{
public static void main(String [] args){
Circle myCircle = new Circle();
Cylinder myCylinder = new Cylinder();
Scanner reader=new Scanner(System.in);
double radius, length;
System.out.println("Enter the radius of the circle");
radius=reader.nextDouble();
myCircle.setRadius(radius);
myCylinder.setRadius(radius);
System.out.println("Enter the height of the cylinder");
length=reader.nextDouble();
myCylinder.setLength(length);
System.out.println("The area of circle is: " +
myCircle.findArea());
System.out.println("The volume of cylinder is: " +
myCylinder.findVolume());
}
}

The final Modifier


 The final class cannot be extended. It prevents inheritance
final class Math{…}

2
 The final method cannot be modified by its subclasses. Final prevents overriding e.g.
public class A{
final void mean() {…}
puclic class B extends A {
void mean() // gets error …}

The Object Class


The Object class is the root of all Java classes. The following are some of the methods of Object class
 The toString() method returns a string representation of the object.
 The equals() method compares the contents of two objects.
 The clone() method copy objects

POLYMORPHISM
Polymorphism refers to the ability to determine at runtime which code to run, given multiple methods with the
same name but different operations in the same class or in different classes. This ability is also known as
dynamic binding.

Overriding Methods
This is creating a method in the subclass that is already defined in the superclass. The ability of a subclass to
override a method in its superclass allows programmers to hide methods in the superclass that are not needed or
that need to be implemented differently.
The return type, method name, number and type of the parameters for the overriding method must match those
in the overridden method. The access modifier for the overriding method can allow more access than the
overridden method, but not less. For example, a protected method in the superclass can be made public but
not private. To call the overridden method, use the super keyword. For example,
super.overriddenMethodName();
A subclass cannot override methods that are declared final in the superclass. Also, a subclass cannot override
methods that are declared static in the superclass (class method). However, a subclass can hide a static method
in the superclass. Overridden methods allow java to support run time polymorphism.

Hiding Member Variables


This is defining a variable in the subclass that is already defined in the superclass. Consider the following
superclass and subclass pair:

public class Super {


float aNumber;
}
public class Sub extends Super {
float aNumber;
}

In the above illustration, the aNumber variable in Sub hides aNumber in Super. This makes it impossible for the
Sub to inherit aNumber variable from the Super unless the keyword super is used, that is,
super.aNumber
super is a Java language keyword that allows a method to refer to hidden variables and overridden methods of
the superclass.

Using super to call super class constructors:


A subclass can call a constructor defined by its super class by use of super keyword.
super(parameter_list);
Super must be the first statement executed inside a subclass constructor.

3
Example
Write a Java program to determine the area of rectangle and circle. The program consist of the parent class
shape and two other classes for finding the area of rectangle and circle respectively. All classes uses
constructors to initialize the data members and have a method Area (), which is used to calculate and display
the area of the respective shapes. Include the Main method to show the working of your program

class Shape {
double d1, d2;
Shape (double d1, double d2) {
this.d1 = d1 ;
this.d2 = d2 ;
}
double area(){
System.out.println("Area of Shape");
return 0;
}
}
class Rectangle extends Shape {
Rectangle (double a, double b){
super(a,b);
}
double area() {
System.out.println("Area of Reatangle");
return d1 * d2;
}
}
class Triangle extends Shape {
Triangle(double a, double b){
super(a,b);
}
double area() {
System.out.println("Area of Triangle");
return (d1 * d2) / 2;
}
}
public class MainClass {
public static void main(String[] args) {
Shape[]shape={new Shape(10,10),new Rectangle(9,5),new Triangle(10,8)};
int index=0;
while (index<3){
System.out.println("Area is = " + shape[index++].area());
}
}
}

ABSTRACT CLASSES AND METHODS:


An abstract class is a class that can only be subclassed (inherited) but cannot be instantiated. To declare that
your class is an abstract class, use the keyword abstract before the class keyword in your class declaration:
abstract class Number {
...
}

An abstract method is a method with no implementation and must be declared using an extra abstract keyword.
An abstract class is not required to have an abstract method in it, but any class that has an abstract method in it,

4
or that does not provide an implementation for any abstract methods declared in its superclasses, must be
declared as an abstract class.
An abstract class is used to define a complete programming interface, thereby providing its subclasses with the
method declarations for all of the methods necessary to implement that programming interface. However, the
abstract class can leave some or all of the implementation details of those methods up to its subclass.
Note: An abstract class can not be directly instantiated with new operator also cannot declare abstract
constructors or abstract static methods.

Example
abstract class Shape {
double d1, d2;
Shape(double d1, double d2) {
this.d1 = d1 ;
this.d2 = d2 ;
}
abstract double area() ;
}
class Rectangle extends Shape {
Rectangle(double a, double b){
super(a,b);
}
double area() {
System.out.println("Area of Rectangle");
return d1 * d2;
}
}
class Triangle extends Shape {
Triangle(double a, double b){
super(a,b);
}
double area() {
System.out.println("Area of Triangle");
return (d1 * d2) / 2;
}
}
public class MainClass {
public static void main(String[] args) {
Shape[]shape={new Rectangle(9,5),new Triangle(10,8)};
int index=0;
while (index<2){
System.out.println("Area is = " +
shape[index++].area());
}
}
}

INTERFACES:
An interface defines a protocol of behavior that can be implemented by any class anywhere in the class
hierarchy. It is generally a collection of unimplemented methods and data items i.e. a class with nothing but
abstract methods and final static, fields. It specifies what a class must do, but not how to do it. The separation
of interface from implementation is a good example of object-oriented design

5
This term is different from the one used in GUI. The term interface as defined above refers to a list of public
methods provided by a class. A class that implements an interface must implement all of the methods declared
in that interface.
Interfaces are useful for the following:
 Capturing similarities among unrelated classes without artificially forcing a class relationship.
 Declaring methods that one or more classes are expected to implement.
 Revealing an object's programming interface without revealing its class.

An interface differs from an abstract class in the following ways:


1. An interface cannot implement any methods, whereas an abstract class can.
2. A class can implement many interfaces but can have only one superclass.
3. An interface is not part of the class hierarchy. Unrelated classes can implement the same interface.

Defining an Interface
Defining an interface is similar to creating a new class. An interface definition has two components: the
interface declaration and the interface body.
interfaceDeclaration {
interfaceBody
}
The interfaceDeclaration declares various attributes about the interface such as its name and whether it extends
another interface. The interfaceBody contains the constant and method declarations within the interface. All
methods declared in an interface are implicitly public and abstract.
An interface can contain constant declarations in addition to method declarations. All constant values defined in
an interface are implicitly public, static, and final.

Syntax
interface Interfacename {
variables declaration ;
methods declaration ;
}

 Variables are declared as follows :


static final type variable_name = value;
 Methods are declared as follows :
return_type methodname (parameter_list);

Example
interface Item {
static final int code = 1000;
void display();
}

Extending an Interface:
Interfaces can also be extended.

interface name2 extends name1 {


body of name2
}

6
Implementing an Interface
To use an interface, you write a class that implements the interface. When a class claims to implement an
interface, the class is claiming that it provides a method implementation for all of the methods declared within
the interface (and its superinterfaces).

class classname extends superclass implements interface1, interface2, … {


body of classname
}

Using an Interface as a Type


When you define a new interface you are in essence defining a new reference data type. You can use interface
names anywhere you'd use any other type name: variable declarations, method parameters and so on.

Example
Write a Java program to determine the area and perimeter of a circle, rectangle and triangle. Your program
consist of an interface and classes that implements the interface and used to compute for the area and perimeter
of the respective shapes. All classes uses constructors to initialize the data members. Include a main class to
demonstrate the working of your program. Provide the UML diagram for your solution

interface Shape {
double area();
double perimeter();
}

// Represents circles.
class Circle implements Shape {
private double radius;
// Constructs a new circle with the given radius.
public Circle(double radius) {
this.radius = radius;
}
// Returns the area of this circle.
public double area() {
return Math.PI * radius * radius;
}
// Returns the perimeter of this circle.
public double perimeter() {
return 2.0 * Math.PI * radius;

7
}
}

// Represents rectangles.
class Rectangle implements Shape {
private double width, height;
// Constructs a new rectangle with the given dimensions.
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
// Returns the area of this rectangle.
public double area() {
return width * height;
}
// Returns the perimeter of this rectangle.
public double perimeter() {
return 2.0 * (width + height);
}
}

// Represents triangles.
class Triangle implements Shape {
private double a, b, c;
// Constructs a new Triangle given side lengths.
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
// Returns this triangle's area using Heron's formula.
public double area() {
double s = (a + b + c) / 2.0;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
// Returns the perimeter of this triangle.
public double perimeter() {
return a + b + c;
}
}

public class DemoInterface{


public static void printInfo(Shape s) {
System.out.println("The shape: " + s);
System.out.println("area : " + s.area());
System.out.println("perim: " + s.perimeter());
System.out.println();
}
public static void main(String[] args){
Shape[] shapes = {new Circle(12.0), new Rectangle(4, 7), new
Triangle(5, 12, 13)};

8
for (int i = 0; i < shapes.length; i++) {
printInfo(shapes[i]);
}
}
}

You might also like