Session 17 - Inheritance - Part 1
Session 17 - Inheritance - Part 1
THROUGH JAVA
UNIT - III
1.
1. What is Inheritance?
Inheritance allows a class (known as the child or subclass) to inherit fields and methods from
another class (known as the parent or superclass). This concept promotes code reuse and
method overriding, facilitating a more organized and hierarchical structure of code.
Key Concepts:
● Superclass (Parent Class): The class from which properties and methods are inherited.
● Subclass (Child Class): The class that inherits properties and methods from the
superclass.
● extends Keyword: - Used to establish an inheritance relationship.
2. Syntax
To create a subclass that inherits from a superclass, use the extends keyword.
class Superclass {
// Superclass code
}
● Code Reusability: Inheritance allows subclasses to reuse the code written in the
superclass. This means that you can create new classes with the same functionality as
existing ones without duplicating code.
● Method Overriding: Inheritance enables method overriding, which is a way to provide
specific implementations of methods in the subclass that are already defined in the
superclass. This supports runtime polymorphism.
● Abstraction: Inheritance allows abstraction by hiding the implementation details in the
superclass while providing a simplified interface to the user.
● Class: A template or blueprint from which objects are created. It defines common
characteristics and behaviors.
● Super Class/Parent Class: The class whose features are inherited. It is also known as
the base class.
● Sub Class/Child Class: The class that inherits from another class. It can add new fields
and methods in addition to those inherited from the superclass.
● Reusability: The ability to use existing class code to create new classes, thereby
avoiding code duplication.
Superclass:
// Animal.java
public class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
Subclass:
// Dog.java
public class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
Main Program:
// Main.java
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Method from superclass
dog.bark(); // Method from subclass
}
}
Output:
2. Types of Inheritance
Inheritance Types
Java supports several types of inheritance, each with its unique characteristics. Below are the
different types of inheritance supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
Definition: In single inheritance, a subclass (child class) is derived from only one superclass
(parent class). The subclass inherits the properties and behavior (methods) of a single parent
class.
Syntax:
class Superclass {
// Fields and methods
}
// Child class
class Two extends One {
public void print_for() {
System.out.println("for");
}
}
// Driver class
public class Main {
public static void main(String[] args) {
Two g = new Two();
g.print_geek(); // Inherited method
g.print_for(); // Method in subclass
}
}
Output:
Geeks
for
Picture:
Explanation: The Two class inherits the print_geek() method from One and has its own
method print_for().
2. Multilevel Inheritance
Definition: In multilevel inheritance, a class is derived from another derived class, forming a
chain of inheritance. The base class is at the top of the chain, with subsequent derived classes
extending the previous class.
Syntax:
class Grandparent {
// Fields and methods
}
// Parent class
class Two extends One {
public void print_for() {
System.out.println("for");
}
}
// Child class
class Three extends Two {
public void print_lastgeek() {
System.out.println("Geeks");
}
}
// Driver class
public class Main {
public static void main(String[] args) {
Three g = new Three();
g.print_geek(); // Inherited from One
g.print_for(); // Inherited from Two
g.print_lastgeek(); // Method in Three
}
}
Output:
Geeks
for
Geeks
Picture:
Explanation: The Three class inherits methods from both One and Two, demonstrating the
chain of inheritance.
3. Hierarchical Inheritance
Definition: In hierarchical inheritance, one superclass is inherited by multiple subclasses. All
subclasses share a common base class.
Syntax:
class Superclass {
// Fields and methods
}
// Subclass 1
class B extends A {
public void print_B() {
System.out.println("Class B");
}
}
// Subclass 2
class C extends A {
public void print_C() {
System.out.println("Class C");
}
}
// Driver Class
public class Test {
public static void main(String[] args) {
B obj_B = new B();
obj_B.print_A(); // Inherited from A
obj_B.print_B(); // Method in B
Class A
Class B
Class A
Class C
Picture:
Explanation: Classes B and C both inherit the print_A() method from class A, each with their
own additional methods.
Syntax:
interface Interface1 {
void method1();
}
interface Interface2 {
void method2();
}
// Interfaces
interface One {
void print_geek();
}
interface Two {
void print_for();
}
// Implementing class
class Child implements One, Two {
public void print_geek() {
System.out.println("Geeks");
}
// Driver class
public class Main {
public static void main(String[] args) {
Child c = new Child();
c.print_geek(); // Method from One
c.print_for(); // Method from Two
}
}
Output:
Geeks
for
Picture:
Explanation: The Child class implements methods from both One and Two interfaces.
5. Hybrid Inheritance
Definition: Hybrid inheritance is a mix of two or more inheritance types, such as combining
multilevel and hierarchical inheritance. Java does not support hybrid inheritance involving
multiple inheritance through classes, but it can be achieved through interfaces.
Example:
interface InterfaceB {
void methodB();
}
class Base {
void baseMethod() {
System.out.println("Base method");
}
}
// Hybrid class
class Derived extends Base implements InterfaceA, InterfaceB {
public void methodA() {
System.out.println("Method A");
}
// Driver class
public class Test {
public static void main(String[] args) {
Derived obj = new Derived();
obj.baseMethod(); // Method from Base
obj.methodA(); // Method from InterfaceA
obj.methodB(); // Method from InterfaceB
}
}
Output:
Base method
Method A
Method B
Picture:
Explanation: The Derived class demonstrates hybrid inheritance by combining class
inheritance and interface inheritance.
Do It Yourself
1. Write a Java program where a Person class has fields name and age, and a subclass
Employee that adds an employeeID field. Implement methods to display all the
information.
4. Define interfaces Flyable and Swimmable with methods fly() and swim()
respectively. Implement these interfaces in a Duck class. Demonstrate both
functionalities in the main() method.
5. Create a Vehicle class with a speed field. Extend it to Car and Bike classes.
Implement an interface Electric with methods charge() and plugIn().
Demonstrate hybrid inheritance by creating an ElectricCar class that extends Car
and implements Electric.
Quiz
Answer: b) Interfaces
4. In which type of inheritance does a class inherit properties from two or more
parent classes?
a) Single Inheritance
b) Multilevel Inheritance
c) Hierarchical Inheritance
d) Multiple Inheritance
Answer: d) Multiple Inheritance
3. Object Class
Object Class
Introduction
In Java programming, the Object class is fundamental as it serves as the root class for all
other classes. Every class in Java either directly or indirectly extends the Object class.
Understanding the Object class is crucial for effective Java programming as it allows for the
implementation of essential functionalities.
Overview
The Object class is part of the java.lang package and is the ultimate superclass of all
classes in Java. Every class inherits from Object, either explicitly or implicitly, which provides
common functionalities and facilitates features like polymorphism.
@Override
public String toString() {
return "Car(brand='" + brand + "', year=" + year + ")";
}
Car(brand='Toyota', year=2022)
1. hashCode() Method
import java.util.Objects;
@Override
public int hashCode() {
return Objects.hash(title, author);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Point other = (Point) obj;
return x == other.x && y == other.y;
}
System.out.println(point1.equals(point2)); // true
System.out.println(point1.equals(point3)); // false
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Employee other = (Employee) obj;
return Objects.equals(name, other.name) && age == other.age;
}
2. Overriding hashCode() Method
@Override
public int hashCode() {
return Objects.hash(name, age);
}
The Object class is a cornerstone of Java programming. Understanding its methods and
proper usage is essential for effective Java development. By mastering the Object class, you
can enhance code reusability, implement polymorphism, and leverage powerful object-oriented
features.
Do It Yourself
1. Implement a class Student with name, id, and grade attributes. Override the
toString(), equals(), and hashCode() methods.
2. Write a program that creates an array of objects of a custom class and demonstrates
how the equals() and hashCode() methods are used in a HashSet.
3. Create a class Rectangle with length and width attributes. Override the
toString() method to return the area of the rectangle.
4. Implement a class Vehicle with make and model attributes. Write a program to
demonstrate the usage of `getClass()` method.
Quiz
Answer: C) toString()
2. What is the return type of the hashCode() method in the Object class?
A) String
B) int
C) void
D) boolean
Answer: B) int
Answer: C) hashCode()
4. What does the getClass() method return?
A) Class name as a String
B) An integer representing the class
C) The runtime class of the object
D) The superclass of the object
Syntax
To declare a class as final, simply use the final keyword in the class declaration:
Examples
Practice Programs
1. Create a final Class: Define a final class named Configuration with some static
fields. Attempt to extend this class in another class and observe the compiler error.
2. Immutable Class Example: Write a final class named Point with x and y
coordinates. Include methods to access these coordinates but no methods to modify
them.
Do It Yourself
1. Write a final class named Constants with constant values for PI and E. Attempt to
extend this class in another class and describe the error.
2. Implement a final class named Employee with private fields for name and id. Provide
a constructor and getter methods but no setters.
4. Discuss how marking a class as final can influence performance optimizations in the
JVM.
5. Design a final class for a configuration settings manager that any other class should
not alter.
Quiz
3. Given the following class declaration, what will the compiler output if you attempt
to extend it?
Answer: A) When you want to create a class that should not be subclassed.
Introduction
Access control is a fundamental concept in Java that defines the visibility and accessibility of
classes, methods, and fields within an application. Proper use of access control ensures that
classes and their members are used in the intended manner, enhancing encapsulation and
security. Inheritance allows one class to acquire the properties and behaviors of another class.
Understanding how access control interacts with inheritance is crucial for designing robust and
maintainable Java applications.
Syntax
1. Public Access Modifier
class PackageClass {
int defaultField;
void defaultMethod() {
// method body
}
}
4. Private Access Modifier
void sleep() {
System.out.println("Sleeping...");
}
// Subclass
public class Dog extends Animal {
public void displayInfo() {
System.out.println("Name: " + name); // public field accessible
System.out.println("Age: " + age); // protected field accessible
// System.out.println("Weight: " + weight); // default field not accessible
(if in a different package)
// System.out.println("Color: " + color); // private field not accessible
}
@Override
public void makeSound() {
System.out.println("Bark");
}
// @Override
// protected void walk() { // private method not accessible
// System.out.println("Dog walking...");
// }
}
Practice Programs
1. Access Control Test
Create a superclass with various access modifiers and a subclass that tries to access
these members. Observe which members are accessible and which are not.
// Superclass
public class Super {
public int pubField = 1;
protected int proField = 2;
int defField = 3; // default access
private int priField = 4;
// Subclass
public class Sub extends Super {
public void testAccess() {
System.out.println(pubField); // Accessible
System.out.println(proField); // Accessible
System.out.println(defField); // Accessible if in the same package
// System.out.println(priField); // Not Accessible
pubMethod(); // Accessible
proMethod(); // Accessible
defMethod(); // Accessible if in the same package
// priMethod(); // Not Accessible
}
}
2. Encapsulation Example
Design a class that uses private fields and provide public methods to access these
fields. Create a subclass that tries to interact with the superclass's fields through public
methods.
Understanding access control and its interaction with inheritance is essential for writing robust
Java applications. By properly using access modifiers, you can ensure that your classes and
their members are encapsulated, secure, and correctly exposed or hidden as needed. This
promotes better design practices and helps maintain the integrity of your code.
Do It Yourself
1. Access Control Analysis: Given a superclass with fields and methods using all access
modifiers, write a subclass and determine which fields and methods are accessible.
2. Encapsulation Exercise: Implement a class with private fields and provide public getter
and setter methods. Write a subclass that uses these methods to access and modify the
fields.
3. Inheritance and Access Control: Explain how access control affects inheritance.
Provide examples demonstrating public, protected, default, and private access in
inheritance.
4. Modify Visibility: Change the access level of certain fields and methods in a class and
observe how these changes affect subclass behavior.
5. Class Design: Design a class hierarchy where a superclass provides general methods
and a subclass extends it with more specific implementations. Use different access
levels for methods and fields to control visibility.
Quiz
Answer: D) public
2. Which access modifier allows a member to be accessed only within its own
package and subclasses?
A) private
B) protected
C) default
D) public
Answer: B) protected
3. If a class has a private field, how can this field be accessed in a subclass?
A) Directly, if the subclass is in the same package.
B) Directly, if the subclass is in a different package.
C) Through a public method in the superclass.
D) Through reflection only.
5. What will be the output if you try to access a default field from a subclass
located in a different package?
A) The field will be accessible.
B) The field will not be accessible.
C) The field will be accessible only through reflection.
D) The compiler will ignore the field.
6. Multilevel Inheritance
Multilevel Inheritance
Introduction
Multilevel inheritance is a type of inheritance in object-oriented programming where a class is
derived from another derived class, forming a hierarchy. This means a class can inherit from
another class that is itself derived from another class. This concept allows for the creation of a
chain of classes, each inheriting the properties and methods of the class above it.
Syntax
In Java, the syntax for multilevel inheritance involves creating a chain of classes where each
class extends the previous class:
Example
Let's illustrate multilevel inheritance with a practical example of a class hierarchy representing
different types of employees in a company:
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("ID: " + id);
}
}
// Derived class
class Manager extends Employee {
String department;
void displayManagerInfo() {
displayInfo();
System.out.println("Department: " + department);
}
}
void displayTeamLeadInfo() {
displayManagerInfo();
System.out.println("Project: " + project);
}
}
Explanation
1. Class Employee: The base class with common attributes name and id, and a method
to display these details.
2. Class Manager: Inherits from Employee and adds a new attribute department. It
includes a method to display the manager’s details.
3. Class TeamLead: Inherits from Manager and adds another attribute project. It
includes a method to display the team lead’s details.
In this hierarchy:
Multilevel inheritance allows the creation of complex class hierarchies, enabling code reuse and
the organization of classes in a structured manner. By understanding and implementing
multilevel inheritance, students can design more flexible and scalable object-oriented systems.
Do It Yourself
1. Create a multilevel inheritance hierarchy for a library system with classes Library
(base class), Section (intermediate class), and Book (derived class). Implement
methods to manage library operations.
2. Implement a class hierarchy for a zoo with a base class Animal, an intermediate class
Mammal, and a derived class Lion. Include methods to display characteristics at each
level.
3. Create a multilevel inheritance hierarchy with a base class Shape, an intermediate class
Polygon, and a derived class Triangle. Override methods in Triangle to calculate
and display area.
5. Implement a class hierarchy for an educational institution with a base class Person, an
intermediate class Teacher, and a derived class Professor. Demonstrate inheritance
and method overriding.
Quiz
Answer: A) A class inherits from another class which in turn inherits from a third class.
2. In a multilevel inheritance hierarchy, which class can access the methods of its
ancestor classes?
A) Only the direct parent class
B) Only the immediate child class
C) Any descendant class
D) Only the top-level class
3. Given the following hierarchy, which class will have access to the methods of
class Base?
-
class Base {
void methodBase() {}
}
Answer: B) extends
5. If a class C inherits from class B, and class B inherits from class A, which of the
following methods is accessible in class C?
A) Only methods defined in class C
B) Only methods defined in class B
C) Only methods defined in class A
D) Methods defined in class A, B, and C
End of Session - 17