Java for Beginners

September 16th, 2023


Week 3: Inheritance and Polymorphism

Class 5: Introduction to Inheritance

Understanding Inheritance

In Week 2, we explored the concept of classes and objects in Java. This week, we delve into a powerful concept called inheritance. Inheritance allows you to create new classes based on existing ones, inheriting their attributes and methods. It’s a fundamental principle of object-oriented programming.

The Base Class (Superclass)

  • A class from which other classes inherit is called the base class or superclass.
  • It contains common attributes and methods shared by its subclasses.

Subclasses (Derived Classes)

  • Classes that inherit from a superclass are known as subclasses or derived classes.
  • Subclasses inherit the attributes and methods of the superclass.
  • They can also have their own additional attributes and methods.

Why Use Inheritance?

  • Code Reusability: Inheritance promotes code reuse by allowing you to define common functionality in a superclass.
  • Hierarchy: It helps create a hierarchy of classes, where more specific classes inherit from more general ones.

Creating Subclasses

Let’s see how to create subclasses in Java.

// Superclass (Base Class)
class Animal {
    String name;

    public Animal(String name) {
        this.name = name;
    }

    void speak() {
        System.out.println("Animal makes a sound");
    }
}

// Subclass (Derived Class)
class Dog extends Animal {
    public Dog(String name) {
        super(name); // Call the superclass constructor
    }

    // Overriding the speak method
    @Override
    void speak() {
        System.out.println(name + " barks");
    }
}

In this example, we have a superclass Animal with an attribute name and a method speak. We then create a subclass Dog that inherits from Animal and overrides the speak method.

Using Inherited and Overridden Methods

public class Main {
    public static void main(String[] args) {
        Animal animal = new Animal("Generic Animal");
        Dog dog = new Dog("Buddy");

        animal.speak(); // Output: Animal makes a sound
        dog.speak();    // Output: Buddy barks
    }
}

In the Main class, we create objects of both Animal and Dog classes. Notice how the speak method behaves differently in the Dog subclass.

The super Keyword

  • The super keyword is used to call the superclass constructor or access superclass methods and attributes.
  • It is useful when you want to extend the behavior of the superclass’s method.
// In the Dog class
void printDetails() {
    System.out.println("Name: " + name);
    super.speak(); // Call the speak method of the superclass
}

Pop Quiz

Quiz 1: What is inheritance in Java?

  1. A way to hide the implementation details of a class.
  2. A way to create new classes based on existing ones, inheriting their attributes and methods.
  3. A way to restrict access to certain members of a class.
  4. A way to define multiple methods with the same name in a class.

Quiz 2: What is a superclass in Java?

  1. A class that inherits from another class.
  2. A class from which other classes inherit attributes and methods.
  3. A class that cannot have subclasses.
  4. A class with no attributes or methods.

Quiz 3: What is the purpose of the super keyword in Java?

  1. To call the superclass constructor or access superclass methods and attributes.
  2. To override a method in a subclass.
  3. To create a new object from a class.
  4. To define a new attribute in a subclass.

Quiz 4: What is method overriding in Java?

  1. Creating a new method with the same name in a subclass.
  2. Calling a method from the superclass in a subclass.
  3. Replacing the implementation of a method inherited from the superclass in a subclass.
  4. Renaming a method in a subclass.

Quiz 5: Which of the following statements about inheritance is true?

  1. Inheritance is a one-way relationship; a superclass can inherit from its subclass.
  2. A subclass can access private members of its superclass.
  3. Subclasses cannot have their own attributes and methods; they can only inherit from the superclass.
  4. Method overriding is a way to extend or modify the behavior of a method inherited from the superclass.

Answers:

  1. B
  2. B
  3. A
  4. C
  5. D

Homework

  1. Create a superclass named Vehicle with the following attributes:
  • make (String): The make or manufacturer of the vehicle.
  • model (String): The model of the vehicle.
  • year (int): The manufacturing year of the vehicle.

Include a constructor to initialize these attributes and a method named displayInfo to display the make, model, and year of the vehicle.

  1. Create two subclasses, Car and Motorcycle, that inherit from the Vehicle superclass. Each subclass should have its own unique attribute(s) related to cars and motorcycles (e.g., numDoors for cars, engineSize for motorcycles).

  2. Implement constructors in the Car and Motorcycle subclasses that initialize their specific attributes and call the superclass constructor to set the common attributes (make, model, year).

  3. Create instances of both Car and Motorcycle in a separate class (e.g., Main) and set their attributes.

  4. Call the displayInfo method on each instance to display the information about the vehicles.

  5. Write a short paragraph (2-3 sentences) explaining the concept of inheritance and how it is used in your implementation.

Class 6: Polymorphism and Method Overloading

Polymorphism

Polymorphism is another essential concept in object-oriented programming. It allows objects of different classes to be treated as objects of a common superclass. This enables flexibility and extensibility in your code.

Types of Polymorphism

  1. Compile-Time Polymorphism: This occurs at compile time and is also known as method overloading. It involves using the same method name with different parameters.

  2. Run-Time Polymorphism: This occurs at runtime and is also known as method overriding. It involves a subclass providing a specific implementation for a method inherited from the superclass.

Method Overloading

Method overloading, a form of compile-time polymorphism, allows you to define multiple methods with the same name in a class. However, these methods must have different parameter lists (different types or different numbers of parameters).

Example of Method Overloading

class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    double add(double a, double b) {
        return a + b;
    }

    String add(String a, String b) {
        return a + b;
    }
}

In this example, the add method is overloaded three times with different parameter types (int, double, String).

Using Method Overloading

public class Main {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();

        int sumInt = calculator.add(5, 7);
        double sumDouble = calculator.add(3.14, 2.71);
        String concatenated = calculator.add("Hello, ", "world!");

        System.out.println("Sum (int): " + sumInt);
        System.out.println("Sum (double): " + sumDouble);
        System.out.println("Concatenated String: " + concatenated);
    }
}

In this Main class, we create an instance of the Calculator class and call the add method with different parameter types. The appropriate overloaded method is selected based on the arguments provided.

Pop Quiz

Quiz 1: What is polymorphism in Java?

  1. A way to restrict access to certain members of a class.
  2. The ability to treat objects of different classes as objects of a common superclass.
  3. A way to create new classes based on existing ones.
  4. A way to hide the implementation details of a class.

Quiz 2: What is method overloading in Java?

  1. Creating a new method with the same name in a subclass.
  2. Providing a specific implementation for a method inherited from the superclass.
  3. Defining multiple methods with the same name in a class but with different parameters.
  4. Accessing superclass methods and attributes in a subclass.

Quiz 3: What is compile-time polymorphism in Java?

  1. Polymorphism that occurs at runtime.
  2. Polymorphism that involves method overriding.
  3. Polymorphism that occurs at compile time and involves method overloading.
  4. Polymorphism that involves creating subclasses.

Quiz 4: Can you overload methods in Java based solely on their return types?

  1. Yes, you can.
  2. No, you cannot.
  3. It depends on the Java version being used.
  4. Only if the methods have different access modifiers.

Quiz 5: What happens if you overload a method in Java with the same parameter types and the same number of parameters?

  1. The program compiles successfully, and the last overloaded method defined is used.
  2. The program does not compile because method overloading is not allowed in this case.
  3. The program compiles successfully, and the first overloaded method defined is used.
  4. The program throws an exception at runtime.

Answers:

  1. B
  2. C
  3. C
  4. B
  5. A

Homework

  1. Create a superclass Shape with attributes color and area. Define a method calculateArea that sets the area to 0.0 and a method displayInfo that displays the color and area.
  2. Create two subclasses, Circle and Rectangle, that inherit from Shape. Implement methods in the subclasses to calculate and set their respective areas.
  3. Create instances of Circle and Rectangle, calculate and display their areas, and specify colors for each shape.