KB

Inheritance and Polymorphism Flashcards

Inheritance

  • Inheritance is the process where an object acquires the properties of another object.

  • It supports hierarchical classification, enabling manageable knowledge representation.

    • Example: A Golden Retriever is a dog, which is a mammal, which is an animal.

  • Without hierarchies, each object would need explicit definition of all characteristics.

  • Inheritance allows an object to define only unique qualities, inheriting general attributes from its parent.

  • It enables an object to be a specific instance of a more general case.

  • People naturally view the world in a hierarchical way (e.g., animals, mammals, dogs).

  • Abstract animal description includes attributes like size, intelligence, and skeletal system type, as well as behaviors like eating, breathing, and sleeping. This forms the class definition for animals.

  • Mammals, a subclass of animals, have more specific attributes like teeth type and mammary glands.

  • Mammals inherit all attributes from animals; a deeply inherited subclass inherits from all ancestors.

  • Inheritance interacts with encapsulation. Subclasses inherit encapsulated attributes and add specializations.

  • This allows object-oriented programs to grow linearly instead of geometrically.

  • A new subclass inherits all attributes from its ancestors.

Why Use Inheritance?

  • Code Reusability: Superclass code is common to all subclasses, allowing direct use of parent code.

  • Method Overriding: Achieved through inheritance, enabling runtime polymorphism in Java.

  • Abstraction: Achieves abstraction by not requiring all details, showing only functionality to the user.

Inheritance Basics

  • Use the extends keyword to inherit a class.

Example
  • Superclass A and subclass B.

// A simple example of inheritance.
// Create a superclass.
class A {
    int i, j;
    void showij() {
        System.out.println("i and j: " + i + " " + j);
    }
}

// Create a subclass by extending class A.
class B extends A {
    int k;
    void showk() {
        System.out.println("k: " + k);
    }
    void sum() {
        System.out.println("i+j+k: " + (i+j+k));
    }
}

class SimpleInheritance {
    public static void main(String args[]) {
        A superOb = new A();
        B subOb = new B();

        // The superclass may be used by itself.
        superOb.i = 10;
        superOb.j = 20;
        System.out.println("Contents of superOb: ");
        superOb.showij();
        System.out.println();

        /* The subclass has access to all public members of its superclass. */
        subOb.i = 7;
        subOb.j = 8;
        subOb.k = 9;
        System.out.println("Contents of subOb: ");
        subOb.showij();
        subOb.showk();
        System.out.println();
        System.out.println("Sum of i, j and k in subOb:");
        subOb.sum();
    }
}
  • Output:

Contents of superOb:
i and j: 10 20

Contents of subOb:
i and j: 7 8
k: 9

Sum of i, j and k in subOb:
i+j+k: 24
  • Subclass B includes all members of superclass A.

  • subOb can access i and j and call showij().

  • Inside sum(), i and j are directly referred to as part of B.

  • A is a standalone class, and being a superclass doesn't prevent it from being used independently.

  • A subclass can be a superclass for another subclass.

General Form
  • Class declaration inheriting a superclass:
    java class subclass-name extends superclass-name { // body of class }

  • Java doesn't support multiple inheritance (unlike C++).

  • Hierarchy of inheritance can be created where a subclass becomes a superclass.

  • No class can be a superclass of itself.

Example 02
class Calculation {
    int z;

    public void addition(int x, int y) {
        z = x + y;
        System.out.println("The sum of the given numbers:" + z);
    }

    public void Subtraction(int x, int y) {
        z = x - y;
        System.out.println("The difference between the given numbers:" + z);
    }
}

public class My_Calculation extends Calculation {
    int z;

    public void multiplication(int x, int y) {
        z = x * y;
        System.out.println("The product of the given numbers:" + z);
    }

    public static void main(String args[]) {
        int a = 20, b = 10;
        My_Calculation demo = new My_Calculation();
        demo.addition(a, b);
        demo.Subtraction(a, b);
        demo.multiplication(a, b);
    }
}
  • Output:

The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

Types of Inheritance

  1. Single Inheritance

    • A single subclass extends from a single superclass.

    • Example: Class A inherits from class B.

  2. Multilevel Inheritance

    • A subclass extends from a superclass, acting as a superclass for another class.

    • Example: Class B inherits from class A and class C inherits from class B.

  3. Hierarchical Inheritance

    • Multiple subclasses extend from a single superclass.

    • Example: Classes B and C inherit from class A.

Example of Hierarchical Inheritance
class Vehicle {
    double basePrice = 10000;

    public void showPrice() {
        System.out.println("The price of Vehicle is: K." + basePrice);
    }
}

class TwoWheeler extends Vehicle {
    double specialCharges = 0.20; // 0.2 times

    void finalPrice() {
        basePrice = basePrice + (basePrice * specialCharges);
        System.out.println("Final price of bike is: K." + basePrice);
    }
}

// child class
class FourWheeler extends Vehicle {
    double specialCharges = 1.5; // 1 times

    void finalPrice() {
        basePrice = basePrice + (basePrice * specialCharges);
        System.out.println("Final price of car is: K." + basePrice);
    }
}

public class Main {
    public static void main(String[] args) {
        TwoWheeler bike = new TwoWheeler();
        FourWheeler car = new FourWheeler();

        // getting the base price of the vehicle
        bike.showPrice();
        // modifying the base price of the bike
        // by referring to the base price of the vehicle.
        bike.finalPrice();

        // getting the base price of vehicle
        car.showPrice();
        // modifying the base price of car
        // by referring the base price of vehicle.
        car.finalPrice();
    }
}
  1. Multiple Inheritance

    • A single subclass extends from multiple superclasses.

    • Example: Class C inherits from both classes A and B.

    • Note: Java doesn't support multiple inheritance.

  2. Hybrid Inheritance

    • Combination of two or more types of inheritance.

    • Example: Classes B and C inherit from class A, and class D inherits from classes B and C (hierarchical and multiple inheritance).

Polymorphism

  • Polymorphism (from Greek, meaning "many forms") allows one interface to be used for a general class of actions.

  • The specific action is determined by the situation.

  • Consider a stack: integer, floating-point, and character stacks share the same algorithm but store different data.

  • In non-object-oriented languages, different stack routines with different names would be needed.

  • Polymorphism in Java allows a general set of stack routines with the same names.

  • "One interface, multiple methods."

  • Reduces complexity by allowing the same interface for a general class of actions.

  • The compiler selects the specific action (method) for each situation.

  • Programmers only need to remember and use the general interface.

  • Polymorphism in Java:

    • Method Overloading

    • Method Overriding

Method Overloading

  • Occurs when there is more than one method of the same name in the class.

  • Creates multiple methods of the same name in the same class, each working differently.

  • A class has multiple methods with the same name, but different numbers, types, and orders of parameters and return types.

  • Java allows the same name for various functions as long as it can distinguish them by parameter type and number.

Example: Calculate the area of a given object
class Shapes {
    void area() {
        System.out.println("No area!!");
    }

    void area(int r) {
        float CA = (float) 3.14 * r * r;
        System.out.println("Area of a Circle = " + CA);
    }

    void area(double b, double h) {
        double TA = 0.5 * b * h;
        System.out.println("Area of a Triangle = " + TA);
    }

    void area(int l, int b) {
        int RA = l * b;
        System.out.println("Area of a Rectangle = " + RA);
    }
}

public class ManyShapes {
    public static void main(String[] args) {
        Shapes myShape = new Shapes(); // Create a Shapes object

        myShape.area();
        myShape.area(7);
        myShape.area(5.0, 2.4);
        myShape.area(8, 4);
    }
}

Method Overriding

  • In a class hierarchy, when a subclass method has the same name and type signature as a superclass method, the subclass method overrides the superclass method.

  • When an overridden method is called from within a subclass, it refers to the subclass version.

  • The superclass method version is hidden.

Example
// Method overriding.
class A {
    int i, j;

    void AssignA(int a, int b) {
        i = a; 
        j = b;
    }

    // display i and j
    void show() {
        System.out.println("i and j: " + i + " " + j);
    }
}

class B extends A {
    int k;

    void AssignB(int a, int b, int c) {
        //super(a, b);
        i = a; 
        j = b; 
        k = c;
    }

    // display k this overrides show() in A
    void show() {
        System.out.println("i and j: " + i + " " + j);
        System.out.println("k: " + k);
    }
}

public class Override {
    public static void main(String args[]) {
        A SuperOb = new A();
        B subOb = new B();
        SuperOb.AssignA(1, 2);
        subOb.AssignB(3, 4, 5);
        SuperOb.show();
        subOb.show(); // this calls show() in B
    }
}
  • Output:

i and j: 1 2
i and j: 3 4
k: 5
  • When show() is invoked on an object of type B, the version of show() defined within B is used, overriding the version in A.

Polymorphism Types

  1. Static/Compile-Time Polymorphism

    • Resolved at compile-time via Method Overloading.

    • The object behaves differently for the same trigger.

    • Multiple methods in the same class.

      • Varying parameter number.

      • Different parameter types.

      • Different order of parameters (e.g., method(String, long) vs. method(long, String)).

  2. Dynamic/Runtime Polymorphism

    • Dynamic Binding or Dynamic Method Dispatch.

    • The call to an overridden method is resolved dynamically at runtime rather than compile-time.

    • Achieved through Method Overriding.

The super Keyword

  • Similar to the this keyword.

  • Used to:

    1. Differentiate members of superclass from subclass if they have the same names.

    2. Invoke the superclass constructor from subclass.

Differentiating Members of Classes
  • If a class inherits properties from another class and members have the same name, super differentiates them.
    java super.variable; super.method();

Example

class Super_class {
    int num = 20;

    public void display() {
        System.out.println("This is the display method of superclass");
    }
}

class Sub_class extends Super_class {
    int num = 10;

    public void display() {
        System.out.println("This is the display method of subclass");
    }

    public void my_method() {
        // Instantiating subclass
        //Sub_class sub = new Sub_class();

        // Invoking the display() method of super class
        super.display();

        // Invoking the display() method of subclass
        //sub.display();
        display();

        // printing the value of variable num of subclass
        System.out.println("value of the variable named num in sub class:" + num);

        // printing the value of variable num of superclass
        System.out.println("value of the variable named num in super class:" + super.num);
    }
}

class SuperDemo {
    public static void main(String args[]) {
        Sub_class obj = new Sub_class();
        obj.my_method();
    }
}
  • Output:

This is the display method of superclass
This is the display method of subclass
value of the variable named num in sub class:10
value of the variable named num in super class:20
Invoking Superclass Constructor
  • A subclass automatically acquires the default constructor of the superclass.

  • To call a parameterized constructor, use the super keyword.
    java super(values);

Example

class Superclass {
    int age;

    Superclass(int age) {
        this.age = age;
    }

    public void getAge() {
        System.out.println("The value of the variable named age in super class is: " + age);
    }
}

class Subclass extends Superclass {
    Subclass(int age) {
        super(age);
    }
}

public class SuperConstructorDemo {
    public static void main(String args[]) {
        Subclass s = new Subclass(24);
        s.getAge();
    }
}
  • Output:

The value of the variable named age in super class is: 24

Packages

  • Containers for classes to keep the class name space compartmentalized.

  • Allows creating classes named List without collision concerns.

  • Packages are stored hierarchically and explicitly imported.

  • The name of each example class was taken from the same name space.

  • Java provides a way for partitioning the class name space into manageable chunks.

  • The package is both a naming and a visibility control mechanism.

  • Classes inside a package are not accessible outside, offering intimate knowledge within the package.

Defining a Package

  • Include a package command as the first statement in a Java source file.

  • Classes within the file belong to the specified package.
    java package pkg;

  • Example: creates a package called MyPackage.
    java package MyPackage;

  • Java uses file system directories to store packages.

  • .class files for classes declared to be part of MyPackage must be in a directory called MyPackage.

  • Case matters; the directory name must match the package name.

Example
// A simple package
package MyPack;

class Balance {
    String name;
    double bal;

    Balance(String n, double b) {
        name = n;
        bal = b;
    }

    void show() {
        if (bal < 0)
            System.out.print("--> ");
        System.out.println(name + ": $" + bal);
    }
}

class AccountBalance {
    public static void main(String args[]) {
        Balance current[] = new Balance[3];
        current[0] = new Balance("K. J. Fielding", 123.23);
        current[1] = new Balance("Will Tell", 157.02);
        current[2] = new Balance("Tom Jackson", -12.33);

        for (int i = 0; i < 3; i++)
            current[i].show();
    }
}
  • Compiling:

    • Call the file AccountBalance.java and put it in a directory called MyPack.

    • Compile the file.

    • Ensure the resulting .class file is in the MyPack directory.

  • Executing:

    • Execute the AccountBalance class:
      shell >java MyPack.AccountBalance

    • Be in the directory above MyPack or set the CLASSPATH environmental variable appropriately.