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?
- A way to hide the implementation details of a class.
- A way to create new classes based on existing ones, inheriting their attributes and methods.
- A way to restrict access to certain members of a class.
- A way to define multiple methods with the same name in a class.
Quiz 2: What is a superclass in Java?
- A class that inherits from another class.
- A class from which other classes inherit attributes and methods.
- A class that cannot have subclasses.
- A class with no attributes or methods.
Quiz 3: What is the purpose of the super
keyword in Java?
- To call the superclass constructor or access superclass methods and attributes.
- To override a method in a subclass.
- To create a new object from a class.
- To define a new attribute in a subclass.
Quiz 4: What is method overriding in Java?
- Creating a new method with the same name in a subclass.
- Calling a method from the superclass in a subclass.
- Replacing the implementation of a method inherited from the superclass in a subclass.
- Renaming a method in a subclass.
Quiz 5: Which of the following statements about inheritance is true?
- Inheritance is a one-way relationship; a superclass can inherit from its subclass.
- A subclass can access private members of its superclass.
- Subclasses cannot have their own attributes and methods; they can only inherit from the superclass.
- Method overriding is a way to extend or modify the behavior of a method inherited from the superclass.
Answers:
- B
- B
- A
- C
- D
Homework
- 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.
-
Create two subclasses,
Car
andMotorcycle
, that inherit from theVehicle
superclass. Each subclass should have its own unique attribute(s) related to cars and motorcycles (e.g.,numDoors
for cars,engineSize
for motorcycles). -
Implement constructors in the
Car
andMotorcycle
subclasses that initialize their specific attributes and call the superclass constructor to set the common attributes (make
,model
,year
). -
Create instances of both
Car
andMotorcycle
in a separate class (e.g.,Main
) and set their attributes. -
Call the
displayInfo
method on each instance to display the information about the vehicles. -
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
-
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.
-
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?
- A way to restrict access to certain members of a class.
- The ability to treat objects of different classes as objects of a common superclass.
- A way to create new classes based on existing ones.
- A way to hide the implementation details of a class.
Quiz 2: What is method overloading in Java?
- Creating a new method with the same name in a subclass.
- Providing a specific implementation for a method inherited from the superclass.
- Defining multiple methods with the same name in a class but with different parameters.
- Accessing superclass methods and attributes in a subclass.
Quiz 3: What is compile-time polymorphism in Java?
- Polymorphism that occurs at runtime.
- Polymorphism that involves method overriding.
- Polymorphism that occurs at compile time and involves method overloading.
- Polymorphism that involves creating subclasses.
Quiz 4: Can you overload methods in Java based solely on their return types?
- Yes, you can.
- No, you cannot.
- It depends on the Java version being used.
- 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?
- The program compiles successfully, and the last overloaded method defined is used.
- The program does not compile because method overloading is not allowed in this case.
- The program compiles successfully, and the first overloaded method defined is used.
- The program throws an exception at runtime.
Answers:
- B
- C
- C
- B
- A
Homework
- Create a superclass
Shape
with attributescolor
andarea
. Define a methodcalculateArea
that sets the area to 0.0 and a methoddisplayInfo
that displays the color and area. - Create two subclasses,
Circle
andRectangle
, that inherit fromShape
. Implement methods in the subclasses to calculate and set their respective areas. - Create instances of
Circle
andRectangle
, calculate and display their areas, and specify colors for each shape.