0% found this document useful (0 votes)
6 views38 pages

Session 17 - Inheritance - Part 1

This document provides an overview of inheritance in Java, explaining its core concepts, types, and syntax. It discusses the importance of inheritance for code reusability, method overriding, and abstraction, while also detailing various inheritance types such as single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance. Additionally, it introduces the Object class as the universal superclass in Java, outlining its methods and significance in object-oriented programming.

Uploaded by

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

Session 17 - Inheritance - Part 1

This document provides an overview of inheritance in Java, explaining its core concepts, types, and syntax. It discusses the importance of inheritance for code reusability, method overriding, and abstraction, while also detailing various inheritance types such as single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance. Additionally, it introduces the Object class as the universal superclass in Java, outlining its methods and significance in object-oriented programming.

Uploaded by

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

OBJECT-ORIENTED PROGRAMMING

THROUGH JAVA

UNIT - III

Session 17 - Inheritance - Part 1

1.

Introduction to Inheritance in Java


Inheritance is one of the core concepts in Object-Oriented Programming (OOP) and is a
mechanism that allows a new class to inherit properties and behaviors (methods) from an
existing class. This concept helps in code reusability and establishing a hierarchical relationship
between classes.

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
}

class Subclass extends Superclass {


// Subclass code
}

3. Why Do We Need Java Inheritance?

● 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.

4. Important Terminologies Used in Java Inheritance

● 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.

5. Example: Basic Inheritance

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:

This animal eats food.


The dog barks.

Explanation: In this example, Dog inherits the eat() method from Animal and also has its
own method bark().

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
}

class Subclass extends Superclass {


// Additional fields and methods
}

Example:

// Parent class


class One {
public void print_geek() {
System.out.println("Geeks");
}
}

// 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
}

class Parent extends Grandparent {


// Additional fields and methods
}

class Child extends Parent {


// Additional fields and methods
}

Example:

// Grandparent class


class One {
public void print_geek() {
System.out.println("Geeks");
}
}

// 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
}

class Subclass1 extends Superclass {


// Additional fields and methods
}

class Subclass2 extends Superclass {


// Additional fields and methods
}

Example:
// Superclass
class A {
public void print_A() {
System.out.println("Class A");
}
}

// 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

C obj_C = new C();


obj_C.print_A(); // Inherited from A
obj_C.print_C(); // Method in C
}
}

Output:

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.

4. Multiple Inheritance (Through Interfaces)


Definition: Java does not support multiple inheritance with classes but allows it through
interfaces. A class can implement multiple interfaces, inheriting behavior from multiple sources.

Syntax:

interface Interface1 {
void method1();
}

interface Interface2 {
void method2();
}

class ImplementingClass implements Interface1, Interface2 {


public void method1() {
System.out.println("Implementation of method1.");
}

public void method2() {


System.out.println("Implementation of method2.");
}
}

Example:

// 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");
}

public void print_for() {


System.out.println("for");
}
}

// 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 for Multiple Inheritance


interface InterfaceA {
void methodA();
}

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");
}

public void methodB() {


System.out.println("Method B");
}
}

// 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.

2. Create a Device class with a method powerOn(). Extend it to create a SmartDevice


class with a connect() method. Further, extend SmartDevice to create a
Smartphone class with a call() method. Demonstrate usage in the main() method.

3. Implement a School class with a location field and a showLocation() method.


Create subclasses Student and Teacher that add their own fields and methods. Show
inheritance in the main() method.

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

1. Which type of inheritance is demonstrated when a class is inherited by more than


one subclass?
a) Single Inheritance
b) Multilevel Inheritance
c) Hierarchical Inheritance
d) Multiple Inheritance

Answer: c) Hierarchical Inheritance

2. What is the key characteristic of multilevel inheritance?


a) A class inherits from multiple classes.
b) A class is derived from another derived class.
c) A class inherits from a single parent class.
d) Multiple subclasses share a common superclass.

Answer: b) A class is derived from another derived class.

3. Which of the following Java constructs supports multiple inheritance?


a) Classes
b) Interfaces
c) Both classes and interfaces
d) None of the above

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

5. Which statement is TRUE about hybrid inheritance in Java?


a) Hybrid inheritance is achieved through multiple inheritance of classes.
b) Hybrid inheritance combines multiple inheritance with interface inheritance.
c) Hybrid inheritance is not possible in Java.
d) Hybrid inheritance can only be implemented using a single inheritance type.

Answer: b) Hybrid inheritance combines multiple inheritance with interface 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.

Object Class in Java: Description and Characteristics


● Universal Superclass: The Object class is the universal superclass for all classes.
Any class that does not extend another class directly inherits from Object.
● Base for Polymorphism: The Object class provides the foundation for polymorphism,
allowing objects of different classes to be treated as objects of the Object class.
● Default Methods: The Object class provides default implementations of several
methods, which can be overridden to customize behavior.

Methods and Properties of the Object Class


The Object class provides several key methods:
1. equals(Object obj): Compares the current object with the specified object for
equality.

Strqaing text1 = "Hello";


String text2 = "Hello";
System.out.println(text1.equals(text2)); // true

2. hashCode(): Returns a unique integer value associated with the object, useful for
hashing-based data structures.

String text = "Hello";


System.out.println(text.hashCode()); // Example output: -907987551

3. toString(): Returns a string representation of the object. By default, it returns the
class name followed by the object's hash code.

String text = "Hello";


System.out.println(text.toString()); // "Hello"

4. clone(): Creates a shallow copy of the object. The class must implement Cloneable
for this method to work.

// String class does not support cloning.



5. getClass(): Returns the runtime class of the object.

String text = "Hello";


System.out.println(text.getClass()); // class java.lang.String

6. wait(), notify(), notifyAll(): Used for thread synchronization and inter-thread
communication. These methods are used in conjunction with the synchronized
keyword.

How to Use the Object Class in Java Programming


The Object class methods can be invoked on any Java object. Here's an example
demonstrating the use of toString():

public class Car {


private String brand;
private int year;

public Car(String brand, int year) {


this.brand = brand;
this.year = year;
}

@Override
public String toString() {
return "Car(brand='" + brand + "', year=" + year + ")";
}

public static void main(String[] args) {


Car myCar = new Car("Toyota", 2022);
System.out.println(myCar.toString());
}
}

Output:

Car(brand='Toyota', year=2022)

Object Class Methods: Description and Examples

1. hashCode() Method
import java.util.Objects;

public class Book {


private String title;
private String author;

public Book(String title, String author) {


this.title = title;
this.author = author;
}

@Override
public int hashCode() {
return Objects.hash(title, author);
}

public static void main(String[] args) {


Book book1 = new Book("Java Programming", "John Doe");
Book book2 = new Book("Python Basics", "Jane Smith");
System.out.println(book1.hashCode());
System.out.println(book2.hashCode());
}
}

2. toString() Method


The toString() method returns a string representation of the object. It is useful for debugging
and logging purposes.

3. equals(Object obj) Method


public class Point {
private int x;
private int y;

public Point(int x, int y) {


this.x = x;
this.y = y;
}

@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;
}

public static void main(String[] args) {


Point point1 = new Point(2, 3);
Point point2 = new Point(2, 3);
Point point3 = new Point(4, 5);

System.out.println(point1.equals(point2)); // true
System.out.println(point1.equals(point3)); // false
}
}

Best Practices for Using Object Class Methods


● Override equals() and hashCode() Together: Ensure that equals() and
hashCode() are overridden together to maintain consistency.
● Provide Meaningful toString() Representations: Override toString() to provide
a useful description of the object.
● Use instanceof for Type Checking: Use instanceof to check types in the
overridden equals() method.

Overriding Object Class Methods


1. Overriding equals() Method

@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);
}

Object Class and Inheritance


By default, if a class does not explicitly extend another class, it extends Object. This allows for
features such as polymorphism and code reuse across different classes.

Benefits of Object Class in Java


● Code Reusability: Methods and properties of the Object class are reused across
different classes.
● Polymorphism: Allows objects of different classes to be treated as Object types.
● Reflection and Introspection: The getClass() method enables dynamic class
information retrieval.

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

1. Which method in the Object class is used to obtain a string representation of an


object?
A) hashCode()
B) equals()
C) toString()
D) clone()

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

3. Which method must be overridden to ensure the correct behavior in hash-based


collections?
A) clone()
B) toString()
C) hashCode()
D) getClass()

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

Answer: C) The runtime class of the object

5. If a class overrides equals(), what should be done with the hashCode()


method?
A) It should be left as default
B) It should be overridden as well
C) It should be set to zero
D) It should be removed

Answer: B) It should be overridden as well

4. Inhibiting Inheritance of Class Using Final

Inhibiting Inheritance of a Class Using final


In Java, inheritance is a fundamental concept that allows one class to inherit properties and
methods from another. However, there are scenarios where you might want to prevent a class
from being extended by other classes. This is where the final keyword comes into play. By
marking a class as final, you can effectively inhibit its inheritance. This ensures that the
class's implementation remains unchanged and secure from modification through subclassing.

Syntax
To declare a class as final, simply use the final keyword in the class declaration:

final class ClassName {


// class body
}

Once a class is declared as final, no other class can extend it.
Characteristics of a final Class
1. Inhibits Subclassing: A final class cannot be extended. This is useful when you want
to create immutable classes or ensure that a class's behavior is not altered through
inheritance.
2. Security and Integrity: Preventing inheritance can protect the integrity of the class and
prevent unintended modifications.
3. Optimizations: The Java Virtual Machine (JVM) can optimize final classes since it
knows their structure cannot be altered by inheritance.

Examples

Example 1: Simple final Class


final class MathConstants {
public static final double PI = 3.14159;
public static final double E = 2.71828;
}

// This will cause a compile-time error


// class ExtendedMathConstants extends MathConstants { }

In this example, MathConstants is a final class, so it cannot be extended. Attempting to do
so will result in a compile-time error.

Example 2: final Class with Methods


final class Utility {
public static void printMessage(String message) {
System.out.println(message);
}
}

public class Test {


public static void main(String[] args) {
Utility.printMessage("Hello, World!");
}
}

Here, Utility is a final class with a static method. This method can be used directly without
allowing further extension of the Utility class.

How to Use final Class in Java Programming


● Designing Immutable Classes: Use the final keyword to design classes whose
instances should not be modified once created.
● Security: Prevent inheritance of classes that contain critical or sensitive logic that should
not be altered.
● Performance: Some performance optimizations can be applied by the JVM for final
classes.

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.

final class Point {


private final int x;
private final int y;

public Point(int x, int y) {


this.x = x;
this.y = y;
}

public int getX() {


return x;
}

public int getY() {


return y;
}
}

The final keyword in Java is a powerful tool for controlling class inheritance. By declaring a
class as final, you can prevent it from being subclassed, ensuring the integrity and security of
its implementation. Understanding when and how to use the final keyword is essential for
effective Java programming and design.

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.

3. Explain the effect of marking a class as final on inheritance. Provide an example to


illustrate your explanation.

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

1. What happens if you try to extend a final class?


A) The subclass inherits all members of the final class.
B) The subclass can override methods of the final class.
C) The code will compile but will not run.
D) The code will not compile.

Answer: D) The code will not compile.

2. Which of the following classes can be declared final?


A) Abstract class
B) Interface
C) Regular class
D) All of the above

Answer: C) Regular class

3. Given the following class declaration, what will the compiler output if you attempt
to extend it?

final class Example {


// class body
}
A) A runtime error
B) A compile-time error
C) The class will extend successfully
D) None of the above

Answer: B) A compile-time error

4. What is the main benefit of declaring a class as final?


A) It allows modification of the class.
B) It prevents other classes from inheriting it.
C) It makes the class abstract.
D) It allows dynamic method dispatch.

Answer: B) It prevents other classes from inheriting it.

5. In which scenario is it appropriate to use a final class?


A) When you want to create a class that should not be subclassed.
B) When you want to allow inheritance but prevent method overriding.
C) When you want to create an interface.
D) When you want to create an abstract class.

Answer: A) When you want to create a class that should not be subclassed.

5. Access Control and Inheritance

Access Control and Inheritance in Java

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.

Access Modifiers in Java


Java provides four primary access modifiers that determine the visibility of classes, methods,
and fields:

1. public: The member or class is accessible from any other class.


2. protected: The member is accessible within its own package and by subclasses (even
if they are in different packages).
3. default (no modifier): The member is accessible only within its own package.
4. private: The member is accessible only within its own class.

Syntax
1. Public Access Modifier

public class MyClass {


public int publicField;
public void publicMethod() {
// method body
}
}

2. Protected Access Modifier

public class ParentClass {


protected int protectedField;
protected void protectedMethod() {
// method body
}
}

3. Default Access Modifier

class PackageClass {
int defaultField;
void defaultMethod() {
// method body
}
}

4. Private Access Modifier

public class MyClass {


private int privateField;
private void privateMethod() {
// method body
}
}

Access Control and Inheritance


When it comes to inheritance, access control modifiers play a crucial role in determining which
members of a superclass are inherited by a subclass:
1. Public Members: Accessible from anywhere, including subclasses.
2. Protected Members: Accessible within the same package and by subclasses,
regardless of their package.
3. Default Members: Accessible only within the same package. Subclasses in different
packages cannot access default members.
4. Private Members: Not accessible from subclasses. They are only accessible within the
class where they are defined.

Example: Access Control in Inheritance


// Superclass
public class Animal {
public String name;
protected int age;
int weight; // default access
private String color;

public void makeSound() {


System.out.println("Some sound");
}

protected void eat() {


System.out.println("Eating...");
}

void sleep() {
System.out.println("Sleeping...");
}

private void walk() {


System.out.println("Walking...");
}
}

// 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...");
// }
}

How to Use Access Control with Inheritance


● Designing APIs: Use public methods for the functionality that needs to be exposed and
protected methods for functionality that subclasses need to use.
● Encapsulation: Use private fields and methods to encapsulate the internal state and
behavior of a class.
● Package Organization: Use default access for classes and members that are intended
to be used within the same package but not exposed to other packages.

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;

public void pubMethod() {}


protected void proMethod() {}
void defMethod() {}
private void priMethod() {}
}

// 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.

public class Person {


private String name;
private int age;

public void setName(String name) {


this.name = name;
}

public String getName() {


return name;
}

public void setAge(int age) {


this.age = age;
}

public int getAge() {


return age;
}
}

public class Student extends Person {


public void displayInfo() {
setName("John");
setAge(20);
System.out.println("Name: " + getName());
System.out.println("Age: " + getAge());
}
}

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

1. Which access modifier allows a member to be accessible from any class?


A) protected
B) private
C) default
D) public

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.

Answer: C) Through a public method in the superclass.

4. Which of the following is NOT accessible in a subclass?


A) protected fields
B) default fields (if in a different package)
C) public methods
D) private methods

Answer: D) private methods

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.

Answer: B) The field will not be accessible.

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:

// Base class


class A {
void methodA() {
System.out.println("Method in class A");
}
}

// Derived class from A


class B extends A {
void methodB() {
System.out.println("Method in class B");
}
}

// Further derived class from B


class C extends B {
void methodC() {
System.out.println("Method in class C");
}
}

Example
Let's illustrate multilevel inheritance with a practical example of a class hierarchy representing
different types of employees in a company:

1. Base Class: Employee


2. Intermediate Class: Manager (inherits from Employee)
3. Derived Class: TeamLead (inherits from Manager)

// Base class


class Employee {
String name;
int id;

Employee(String name, int id) {


this.name = name;
this.id = id;
}

void displayInfo() {
System.out.println("Name: " + name);
System.out.println("ID: " + id);
}
}

// Derived class
class Manager extends Employee {
String department;

Manager(String name, int id, String department) {


super(name, id);
this.department = department;
}

void displayManagerInfo() {
displayInfo();
System.out.println("Department: " + department);
}
}

// Further derived class


class TeamLead extends Manager {
String project;

TeamLead(String name, int id, String department, String project) {


super(name, id, department);
this.project = project;
}

void displayTeamLeadInfo() {
displayManagerInfo();
System.out.println("Project: " + project);
}
}

// Test the classes


public class TestInheritance {
public static void main(String[] args) {
TeamLead lead = new TeamLead("John Doe", 123, "IT", "Project A");
lead.displayTeamLeadInfo();
}
}

Output:

Name: John Doe


ID: 123
Department: IT
Project: Project A

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:

● Employee is the top-level class.


● Manager inherits from Employee.
● TeamLead inherits from Manager.

1. Multilevel Inheritance Diagram:

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.

4. Design an employee management system with a base class Employee, an intermediate


class Manager, and a derived class Director. Include methods to display the
hierarchy and employee details.

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

1. Which of the following correctly describes multilevel inheritance?


A) A class inherits from another class which in turn inherits from a third class.
B) A class inherits from multiple classes.
C) Multiple classes inherit from a single class.
D) A class is derived from multiple classes.

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

Answer: C) Any descendant class

3. Given the following hierarchy, which class will have access to the methods of
class Base?
-
class Base {
void methodBase() {}
}

class Derived1 extends Base {}

class Derived2 extends Derived1 {}


A) Only Base
B) Derived1 and Derived2
C) Only Derived2
D) Only Derived1

Answer: B) Derived1 and Derived2

4. Which keyword is used to extend a class in Java?


A) implements
B) extends
C) inherits
D) derives

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

Answer: D) Methods defined in class A, B, and C


References

End of Session - 17

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy