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

Session 18 - Inheritance - Part 2

This document covers the application of the 'super' keyword in Java, which allows subclasses to access superclass methods, constructors, and fields. It includes syntax examples, explanations of calling superclass constructors, accessing methods, and fields, as well as practical applications and quizzes. Additionally, it discusses the role of constructors in inheritance, method overriding, and provides exercises to reinforce understanding.

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)
2 views38 pages

Session 18 - Inheritance - Part 2

This document covers the application of the 'super' keyword in Java, which allows subclasses to access superclass methods, constructors, and fields. It includes syntax examples, explanations of calling superclass constructors, accessing methods, and fields, as well as practical applications and quizzes. Additionally, it discusses the role of constructors in inheritance, method overriding, and provides exercises to reinforce understanding.

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 18 - Inheritance - Part 2

1. Application of Keyword Super

Application of the Keyword super in Java

Introduction
In Java, the keyword super is used to refer to the superclass (parent class) of the current
object. It provides a way to access superclass methods and constructors, and to resolve
ambiguities between superclass and subclass members. The super keyword can be used in
several scenarios including calling superclass constructors, accessing superclass methods, and
accessing superclass fields.

Syntax
1. Calling Superclass Constructor:

super(arguments);

2. Accessing Superclass Method:

super.methodName(arguments);

3. Accessing Superclass Field:

super.fieldName;

Examples

1. Calling Superclass Constructor


When a subclass is instantiated, its constructor can call the constructor of its superclass using
super() to initialize inherited fields.

class Animal {
String name;

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

class Dog extends Animal {


Dog(String name) {
super(name); // Calls the constructor of Animal
}

void display() {
System.out.println("Dog's name is: " + name);
}
}

public class TestSuper {


public static void main(String[] args) {
Dog dog = new Dog("Buddy");
dog.display();
}
}

Output:

Dog's name is: Buddy

2. Accessing Superclass Method


If a subclass overrides a method from its superclass, super can be used to call the superclass
version of that method.

class Parent {
void show() {
System.out.println("Parent class method");
}
}

class Child extends Parent {


void show() {
super.show(); // Calls the show() method of Parent
System.out.println("Child class method");
}
}

public class TestSuper {


public static void main(String[] args) {
Child child = new Child();
child.show();
}
}

Output:

Parent class method


Child class method

3. Accessing Superclass Field


In case of field hiding, super is used to access the field of the superclass.

class Parent {
int x = 10;
}

class Child extends Parent {


int x = 20;

void display() {
System.out.println("Parent x: " + super.x); // Accesses x from Parent
System.out.println("Child x: " + x); // Accesses x from Child
}
}

public class TestSuper {


public static void main(String[] args) {
Child child = new Child();
child.display();
}
}

Output:

Parent x: 10
Child x: 20

Explanation
● Calling Superclass Constructor: The super keyword can be used to invoke a
constructor of the superclass. This is essential when the superclass constructor requires
parameters to initialize its fields.

● Accessing Superclass Method: When a method in a subclass overrides a method in


the superclass, the super keyword can be used to call the original method from the
superclass. This is useful for extending functionality while preserving the base
functionality.

● Accessing Superclass Field: When a subclass declares a field with the same name as
a field in the superclass, super allows accessing the superclass field to avoid ambiguity.

The super keyword is a fundamental feature in Java that helps manage class hierarchies by
providing access to superclass members. Understanding how to use super effectively is crucial
for leveraging inheritance in Java and ensuring that subclass instances correctly interact with
their superclass elements.

Do It Yourself
1. Implement a base class Vehicle with a parameterized constructor. Create a derived
class Car that uses super() to call the constructor of Vehicle. Add additional
attributes and methods in Car.

2. Define a class Shape with a method draw(). Create a subclass Circle that overrides
draw() and uses super.draw() to call the method in Shape.

3. Implement a base class Animal with a field age. Create a derived class Cat that hides
the age field and use super.age to access the field in Animal.
4. Create a class hierarchy with Base, Intermediate, and Final classes. Use super to
call methods and constructors across the hierarchy.

5. Define a base class Account with a method deposit(). Extend it with


SavingsAccount and CheckingAccount. Override deposit() and use
super.deposit() in each subclass.

Quiz

1. What does the super keyword do in Java?


A) Refers to the superclass constructor, methods, and fields.
B) Creates a new instance of the superclass.
C) Deletes the superclass.
D) Replaces the superclass with the current class.

Answer: A) Refers to the superclass constructor, methods, and fields.

2. Which of the following statements is true about super() in Java?


A) super() must be the first statement in the constructor of a subclass.
B) super() can be called after other statements in the constructor.
C) super() is used to access the methods of the current class.
D) super() cannot be used in a constructor.

Answer: A) super() must be the first statement in the constructor of a subclass.

3. Given the following code, what will be the output?

class A {
void display() {
System.out.println("Class A");
}
}

class B extends A {
void display() {
super.display();
System.out.println("Class B");
}
}

public class Test {


public static void main(String[] args) {
B obj = new B();
obj.display();
}
}
A) Class A Class B
B) Class B Class A
C) Class A
D) Class B

Answer: A) Class A Class B

4. Which keyword is used to access a field from the superclass in Java?


A) this
B) super
C) extends
D) implements

Answer: B) super

5. In the following code, what will be the result of super.x?

class A {
int x = 10;
}

class B extends A {
int x = 20;

void show() {
System.out.println(super.x);
}
}

public class Test {


public static void main(String[] args) {
B obj = new B();
obj.show();
}
}
A) 10
B) 20
C) 30
D) Compilation error

Answer: A) 10

2. Constructor Method and Inheritance

Constructor Method and Inheritance in Java

Introduction
In Java, constructors are special methods used to initialize objects. They are called when an
instance of a class is created. Constructors play a crucial role in inheritance by ensuring that the
superclass is properly initialized before the subclass is instantiated. This document explores the
role of constructors in inheritance, including their syntax, examples, explanations, and practical
applications.

Syntax
1. Constructor Declaration:

ClassName(parameters) {
// constructor body
}

2. Calling Superclass Constructor:

super(arguments);

Examples

1. Basic Constructor in Inheritance


When a subclass is instantiated, the constructor of the superclass is called first, either implicitly
or explicitly. If the superclass has a no-argument constructor, it is called automatically. If the
superclass has a parameterized constructor, you need to use super() to call it.

class Animal {
Animal() {
System.out.println("Animal constructor");
}
}

class Dog extends Animal {


Dog() {
super(); // Calls Animal constructor
System.out.println("Dog constructor");
}
}

public class TestConstructor {


public static void main(String[] args) {
Dog dog = new Dog();
}
}

Output:

Animal constructor
Dog constructor

2. Parameterized Constructor in Inheritance


When the superclass has a parameterized constructor, you must call it from the subclass
constructor using super().

class Animal {
String name;

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

class Dog extends Animal {


Dog(String name) {
super(name); // Calls Animal(String name)
System.out.println("Dog constructor");
}
}

public class TestConstructor {


public static void main(String[] args) {
Dog dog = new Dog("Buddy");
System.out.println("Dog's name: " + dog.name);
}
}

Output:

Dog constructor
Dog's name: Buddy

3. Constructor Overloading in Inheritance


Both the superclass and subclass can have overloaded constructors.

class Animal {
String name;

Animal() {
this.name = "Unknown";
}

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

class Dog extends Animal {


int age;

Dog() {
super(); // Calls Animal()
this.age = 0;
}

Dog(String name, int age) {


super(name); // Calls Animal(String name)
this.age = age;
}
}

public class TestConstructor {


public static void main(String[] args) {
Dog dog1 = new Dog();
Dog dog2 = new Dog("Buddy", 5);
System.out.println("Dog1 name: " + dog1.name + ", age: " + dog1.age);
System.out.println("Dog2 name: " + dog2.name + ", age: " + dog2.age);
}
}

Output:

Dog1 name: Unknown, age: 0


Dog2 name: Buddy, age: 5

Explanation
- Superclass Constructor Call: When a subclass object is created, the constructor of the
superclass is called first. This ensures that the superclass is properly initialized before
the subclass starts its initialization.

- Parameterized Constructors: If a superclass has parameterized constructors, the


subclass must explicitly call one of these constructors using super(). This allows you
to initialize the superclass with specific values.

- Constructor Overloading: Both superclass and subclass can have multiple


constructors with different parameter lists. Constructor overloading allows for different
ways to initialize objects.

Practice Programs
1. Shape Hierarchy: Create a base class Shape with a no-argument constructor and a
parameterized constructor. Extend it with Circle and Rectangle classes that use
both constructors to initialize their properties.

2. Employee Management: Design a base class Employee with constructors for


initializing employee ID and name. Create subclasses FullTimeEmployee and
PartTimeEmployee that call these constructors and add additional fields.

3. Vehicle System: Implement a base class Vehicle with constructors to set make and
model. Extend it with Car and Bike classes that use the superclass constructors and
initialize additional attributes.

4. Person and Student: Create a base class Person with a parameterized constructor.
Extend it with Student that initializes additional attributes using super() and
demonstrates constructor chaining.

5. Library Items: Develop a base class LibraryItem with constructors for item ID and
title. Extend it with Book and Magazine classes that initialize additional properties and
demonstrate constructor overloading.
Understanding constructors and their role in inheritance is essential for managing class
hierarchies in Java. Constructors ensure proper initialization of objects and facilitate the
inheritance mechanism by setting up superclass properties before subclass-specific
initialization. This knowledge is crucial for writing efficient and maintainable Java code.

Do It Yourself
1. Implement a base class Employee with a constructor that initializes name and ID.
Extend it with Manager and Intern classes that use super() to initialize the base
class fields and add additional attributes.

2. Define a base class Animal with a parameterized constructor for setting name and age.
Create a subclass Bird that uses constructor chaining to initialize both the base class
and its own fields.

3. Create a class Person with multiple constructors for name and age. Extend it with
Student and Teacher classes that use different constructors to initialize their fields.

4. Design a class hierarchy with Vehicle as the base class, and Car and Truck as
subclasses. Implement overloaded constructors in each class to handle different
initialization scenarios.

5. Write a program that demonstrates the use of both no-argument and parameterized
constructors in a class hierarchy where Parent and Child classes are involved.

Quiz

1. What happens if a subclass constructor does not explicitly call a superclass


constructor?
A) The subclass constructor will not compile.
B) The default no-argument constructor of the superclass is called automatically.
C) The superclass constructor must be defined as static.
D) The superclass constructor is skipped.
Answer: B) The default no-argument constructor of the superclass is called
automatically.

2. Which keyword is used to invoke a superclass constructor from a subclass?


A) this
B) super
C) extends
D) implements

Answer: B) super

3. Given the following code, what will be the output?

class A {
A(int x) {
System.out.println("A constructor with value: " + x);
}
}

class B extends A {
B() {
super(10);
System.out.println("B constructor");
}
}

public class Test {


public static void main(String[] args) {
B obj = new B();
}
}
A) A constructor with value: 10 B constructor
B) A constructor with value: 10
C) B constructor
D) Compilation error

Answer: A) A constructor with value: 10 B constructor

4. Which of the following is true about constructor overloading in Java?


A) Constructor overloading is not allowed in Java.
B) A subclass can have a constructor with the same name as its superclass.
C) A constructor can be overloaded by changing the return type.
D) Constructor overloading is determined by the number and type of parameters.
Answer: D) Constructor overloading is determined by the number and type of
parameters.

5. What is the result of the following code?

class Parent {
Parent() {
System.out.println("Parent constructor");
}
}

class Child extends Parent {


Child() {
System.out.println("Child constructor");
}
}

public class Test {


public static void main(String[] args) {
Child obj = new Child();
}
}
A) Parent constructor Child constructor
B) Child constructor
C) Parent constructor
D) Compilation error

Answer: A) Parent constructor Child constructor

3. Method Overriding

Method Overriding in Java

Introduction
Method overriding is a fundamental concept in Java's object-oriented programming that allows a
subclass to provide a specific implementation of a method that is already defined in its
superclass. This concept is pivotal for achieving runtime polymorphism, which enables a
program to choose the appropriate method implementation based on the object's runtime type.

Syntax
class Superclass {
void methodName() {
// Superclass method implementation
}
}

class Subclass extends Superclass {


@Override
void methodName() {
// Subclass method implementation
}
}

- @Override Annotation: This annotation is used to indicate that the method is intended
to override a method in the superclass. It is optional but recommended as it helps to
catch errors during compilation.

Examples

1. Basic Method Overriding


In this example, the subclass overrides the display() method of the superclass Animal.

class Animal {
void display() {
System.out.println("This is an animal.");
}
}
class Dog extends Animal {
@Override
void display() {
System.out.println("This is a dog.");
}
}

public class Test {


public static void main(String[] args) {
Animal animal = new Animal();
animal.display(); // Output: This is an animal.

Dog dog = new Dog();


dog.display(); // Output: This is a dog.
}
}

Output:

This is an animal.
This is a dog.

2. Method Overriding with Parameters


The overridden method in the subclass can have the same parameters as the method in the
superclass.

class Vehicle {
void start(String type) {
System.out.println("Starting " + type);
}
}

class Car extends Vehicle {


@Override
void start(String type) {
System.out.println("Car is starting with " + type);
}
}

public class Test {


public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
vehicle.start("engine");

Car car = new Car();


car.start("electricity");
}
}

Output:

Starting engine
Car is starting with electricity

3. Method Overriding with Return Type


In Java, a subclass method can override a superclass method while changing the return type to
a subtype (covariant return type).

class Animal {
Animal getAnimal() {
return this;
}
}

class Dog extends Animal {


@Override
Dog getAnimal() {
return this;
}
}

public class Test {


public static void main(String[] args) {
Dog dog = new Dog();
dog.getAnimal().display();
}
}

Output:

This is a dog.

Explanation
● Method Signature: To override a method, the method signature in the subclass must
exactly match the method signature in the superclass. This includes the method name,
return type, and parameter list.

● Access Modifiers: The overridden method in the subclass can have the same or more
permissive access modifier than the method in the superclass. For example, if the
superclass method is protected, the subclass method can be protected or public,
but not private.

● @Override Annotation: This annotation helps to ensure that the method is correctly
overriding a superclass method and not overloading it. It also improves code readability
and maintainability.

Method overriding is a critical feature in Java that allows subclasses to provide specific
implementations of methods defined in their superclasses. This mechanism supports runtime
polymorphism, enabling flexible and dynamic method invocation. Understanding method
overriding helps in designing robust and maintainable object-oriented systems.

Do It Yourself
1. Implement a base class Vehicle with a method accelerate(). Create a subclass
Bike that overrides accelerate() and demonstrate the use of the overridden method.

2. Write a base class Printer with a method print(String document). Extend it with
LaserPrinter and InkjetPrinter classes that override print() to provide
specific printing implementations.

3. Create a base class Building with a method getType(). Extend it with House and
Skyscraper classes that override getType() to return more specific types.

4. Define a base class Person with a protected method getDetails(). Extend it with
Student and Teacher classes that override getDetails() to provide detailed
information.

5. Design a class hierarchy with a base class Appliance and subclasses


WashingMachine, Refrigerator, and Oven. Override a method function() in
each subclass to demonstrate specific functionalities.

Quiz
1. Which annotation is used to indicate that a method is overriding a superclass
method?
A) @Override
B) @OverrideMethod
C) @Overriding
D) @OverrideMethod

Answer: A) @Override

2. Which of the following is true about method overriding?


A) The method name and return type must be different in the subclass.
B) The method in the subclass must have the same return type or a subtype.
C) Method overriding allows changing the method’s name.
D) The overridden method can have different access modifiers than the method in the
superclass.

Answer: B) The method in the subclass must have the same return type or a subtype.

3. Given the following code, what will be the output?

class Animal {
void sound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog bark");
}
}

public class Test {


public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}
A) Animal sound
B) Dog bark
C) Compilation error
D) Runtime error

Answer: B) Dog bark

4. Which of the following is a valid reason to use method overriding?


A) To increase the method's visibility in the subclass.
B) To call a superclass method in a subclass.
C) To provide a specific implementation of a method in a subclass.
D) To prevent method overriding in subclasses.

Answer: C) To provide a specific implementation of a method in a subclass.

5. What is the result of the following code?

class Base {
void show() {
System.out.println("Base class");
}
}

class Derived extends Base {


void show() {
System.out.println("Derived class");
}
}

public class Test {


public static void main(String[] args) {
Base obj = new Derived();
obj.show();
}
}
A) Base class
B) Derived class
C) Compilation error
D) Runtime error

Answer: B) Derived class

4. Dynamic Method Dispatch


Dynamic Method Dispatch in Java

Introduction
Dynamic Method Dispatch is a core concept in Java that supports runtime polymorphism. It
allows a method to be called based on the actual object type, rather than the reference type, at
runtime. This capability is fundamental to the concept of polymorphism and method overriding in
Java.

Syntax
Dynamic Method Dispatch involves the following key elements:

1. Superclass: Defines a method.


2. Subclass: Overrides the method from the superclass.
3. Reference Variable: Holds a reference to an object of the subclass but is of the type of
the superclass.

Here's a basic syntax outline:

class Superclass {
void display() {
System.out.println("Superclass display");
}
}

class Subclass extends Superclass {


@Override
void display() {
System.out.println("Subclass display");
}
}

public class Test {


public static void main(String[] args) {
Superclass obj = new Subclass(); // Upcasting
obj.display(); // Calls Subclass's display method
}
}

Explanation
- Upcasting: Refers to the process of assigning a subclass object to a superclass
reference. This is essential for dynamic method dispatch.
- Method Overriding: Allows a subclass to provide a specific implementation of a method
already defined in its superclass.
- Runtime Method Resolution: The actual method that gets called is determined at
runtime based on the object's type, not the reference type.

Examples

1. Basic Example of Dynamic Method Dispatch


class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Bark");
}
}

class Cat extends Animal {


@Override
void makeSound() {
System.out.println("Meow");
}
}

public class Test {


public static void main(String[] args) {
Animal myAnimal;

myAnimal = new Dog();


myAnimal.makeSound(); // Output: Bark

myAnimal = new Cat();


myAnimal.makeSound(); // Output: Meow
}
}

Output:

Bark
Meow

2. Dynamic Method Dispatch with Method Overloading


class Printer {
void print(int a) {
System.out.println("Printing integer: " + a);
}
}

class ColorPrinter extends Printer {


@Override
void print(int a) {
System.out.println("Printing integer in color: " + a);
}

void print(String str) {


System.out.println("Printing string in color: " + str);
}
}

public class Test {


public static void main(String[] args) {
Printer printer = new ColorPrinter();
printer.print(10); // Output: Printing integer in color: 10
}
}

Output:

Printing integer in color: 10

Practice Programs
1. Shape Drawing: Create a base class Shape with a method draw(). Derive Circle,
Rectangle, and Triangle classes from it. Override the draw() method in each
derived class. Use dynamic method dispatch to call the draw() method on various
shape objects.

2. Employee Management: Develop a base class Employee with a method


calculateSalary(). Extend it with FullTimeEmployee and PartTimeEmployee
classes. Override calculateSalary() in each subclass and use dynamic method
dispatch to compute salaries.

3. Vehicle System: Implement a base class Vehicle with a method start(). Extend it
with Car, Bike, and Truck classes. Override start() in each subclass. Use dynamic
method dispatch to start different vehicle objects.
4. Media Playback: Define a base class Media with a method play(). Derive Audio and
Video classes from it. Override play() in each subclass. Use dynamic method
dispatch to play different media types.

5. Payment Processing: Create a base class Payment with a method process().


Extend it with CreditCardPayment and PaypalPayment classes. Override
process() in each subclass and use dynamic method dispatch to handle various
payment methods.

Dynamic Method Dispatch is a powerful feature of Java that supports runtime polymorphism,
allowing for flexible and adaptable code. Understanding and applying this concept is crucial for
designing robust and maintainable object-oriented systems.

Do It Yourself
1. Write a program with a base class Animal and derived classes Dog and Cat. Override
the makeSound() method in each derived class. Use dynamic method dispatch to
invoke the makeSound() method.

2. Design a class hierarchy with a base class Vehicle and subclasses Car, Truck, and
Motorcycle. Each subclass should override a method startEngine(). Demonstrate
dynamic method dispatch.

3. Implement a base class Calculator with overloaded add() methods. Extend it with
ScientificCalculator that overrides one of the add() methods. Use dynamic
method dispatch to invoke the overridden method.

4. Create a base class Account with a method getBalance(). Extend it with


SavingsAccount and CheckingAccount classes. Override getBalance() in each
subclass. Use dynamic method dispatch to display account balances.

5. Define a base class Book with a method getDetails(). Extend it with EBook and
PrintedBook classes. Override getDetails() in each subclass and demonstrate
dynamic method dispatch.
Quiz

1. What is Dynamic Method Dispatch?


A) A process of resolving method calls at compile time
B) A process of method overloading
C) A process of method overriding at runtime
D) A process of method hiding

Answer: C) A process of method overriding at runtime

2. In Dynamic Method Dispatch, which method implementation is called?


A) The method in the superclass
B) The method in the subclass
C) The method with the highest access level
D) The method based on the reference type

Answer: B) The method in the subclass

3. Given the following code, what will be the output?

class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Dog barks");
}
}

public class Test {


public static void main(String[] args) {
Animal a = new Dog();
a.makeSound();
}
}
A) Animal sound
B) Dog barks
C) Compilation error
D) Runtime error

Answer: B) Dog barks

4. Which of the following allows a subclass to provide a specific implementation of a


method defined in a superclass?
A) Method Overloading
B) Method Hiding
C) Method Overriding
D) Method Binding

Answer: C) Method Overriding

5. What happens if a method is not overridden in a subclass?


A) The subclass method is invoked
B) The superclass method is called
C) Compilation error occurs
D) Runtime error occurs

Answer: B) The superclass method is called

5. Abstract Classes

Abstract Classes in Java

Introduction
Abstract classes in Java are classes that cannot be instantiated on their own and are intended
to be subclasses. They provide a way to define methods that must be implemented by
subclasses and can also contain concrete methods with implementations. Abstract classes are
a key part of Java's abstraction mechanism and are used to define a common interface for a
group of related classes.

Syntax
1. Declaration: An abstract class is declared using the abstract keyword.
2. Abstract Methods: Methods declared without an implementation using the abstract
keyword.
3. Concrete Methods: Regular methods with an implementation can also be included.
Syntax Example:

abstract class AbstractClass {


abstract void abstractMethod(); // Abstract method (no body)

void concreteMethod() { // Regular method


System.out.println("This is a concrete method.");
}
}

Key Points
- Abstract Methods: Must be implemented by subclasses.
- Concrete Methods: Can have implementations.
- Abstract Class Instantiation: Cannot be instantiated directly.
- Subclassing: Subclasses must implement all abstract methods to be concrete.

Examples

1. Basic Example
abstract class Animal {
abstract void makeSound(); // Abstract method

void sleep() { // Concrete method


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

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Bark");
}
}

public class Test {


public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Bark
myDog.sleep(); // Output: Sleeping
}
}

Output:
Bark
Sleeping

2. Abstract Class with Constructor


abstract class Shape {
String color;

Shape(String color) {
this.color = color;
}

abstract void draw();

void displayColor() {
System.out.println("Color: " + color);
}
}

class Circle extends Shape {


Circle(String color) {
super(color);
}

@Override
void draw() {
System.out.println("Drawing Circle");
}
}

public class Test {


public static void main(String[] args) {
Shape circle = new Circle("Red");
circle.draw(); // Output: Drawing Circle
circle.displayColor(); // Output: Color: Red
}
}

Output:

Drawing Circle
Color: Red
Practice Programs
1. Vehicle Hierarchy: Create an abstract class Vehicle with an abstract method
start(). Extend it with Car and Bike classes that implement the start() method.
Demonstrate the use of abstract class and method overriding.

2. Employee System: Design an abstract class Employee with an abstract method


calculateSalary(). Extend it with FullTimeEmployee and PartTimeEmployee
classes. Implement calculateSalary() in both subclasses and demonstrate their
usage.

3. Shape Drawing: Define an abstract class Shape with an abstract method draw().
Derive Rectangle, Triangle, and Circle classes from it. Implement the draw()
method in each subclass and use an array of Shape to invoke the draw() method.

4. Account Management: Create an abstract class Account with abstract methods


deposit() and withdraw(). Extend it with SavingsAccount and
CheckingAccount classes. Implement the methods in each subclass and demonstrate
their functionality.

5. Appliance System: Implement an abstract class Appliance with an abstract method


operate(). Extend it with WashingMachine and Refrigerator classes. Provide
implementations for operate() and show how these appliances work.

Abstract classes in Java are a fundamental feature for creating a common interface for a group
of related classes, enforcing a structure that subclasses must follow. They allow for the
definition of abstract methods that must be implemented by subclasses while providing the
flexibility to include concrete methods with implementations. Understanding and utilizing
abstract classes is crucial for designing flexible and maintainable object-oriented systems.

Do It Yourself
1. Write a program with an abstract class Appliance that has an abstract method
turnOn(). Create two subclasses, Fan and Light, that implement the turnOn()
method. Display the output of both.
2. Create an abstract class Calculator with an abstract method add(). Implement the
method in a subclass ScientificCalculator with method overloading. Provide
different implementations for adding integers and floating-point numbers.

3. Design an abstract class Book with an abstract method getTitle(). Implement a


concrete class Novel that extends Book, using the constructor to initialize the book's
title. Display the title using the getTitle() method.

4. Implement an abstract class Vehicle with an abstract method fuelEfficiency().


Derive ElectricCar and DieselTruck classes from it. Provide specific
implementations for fuelEfficiency() in both subclasses.

5. Create an abstract class GameCharacter with an abstract method attack().


Implement subclasses Warrior and Mage that override the attack() method.
Demonstrate their attacks.

Quiz

1. Which of the following cannot be done with an abstract class?


A) Create an instance of the class
B) Define abstract methods
C) Define concrete methods
D) Define constructors

Answer: A) Create an instance of the class

2. Which keyword is used to declare an abstract class in Java?


A) abstract
B) interface
C) final
D) static

Answer: A) abstract

3. Given the following code, what will be the output?

abstract class Animal {


abstract void makeSound();
}

class Cat extends Animal {


void makeSound() {
System.out.println("Meow");
}
}

public class Test {


public static void main(String[] args) {
Animal myCat = new Cat();
myCat.makeSound();
}
}
A) Compilation error
B) Runtime error
C) Meow
D) No output

Answer: C) Meow

4. What is the purpose of an abstract method?


A) To provide a complete method implementation
B) To allow method implementation in the subclass
C) To prevent a method from being overridden
D) To allow for multiple implementations in the same class

Answer: B) To allow method implementation in the subclass

5. Which of the following statements is true about an abstract class?


A) An abstract class can be instantiated directly.
B) An abstract class can have both abstract and concrete methods.
C) An abstract class cannot have constructors.
D) All methods in an abstract class must be abstract.

Answer: B) An abstract class can have both abstract and concrete methods
6. Interfaces and Inheritance

Interfaces and Inheritance in Java

Introduction
In Java, interfaces and inheritance are two fundamental concepts that support polymorphism
and abstraction. While inheritance allows a class to inherit properties and methods from another
class, interfaces provide a way to define a contract that classes can implement. Understanding
how to use both effectively can lead to more flexible and maintainable code.

Interfaces in Java

Syntax
1. Declaration: An interface is declared using the interface keyword.
2. Methods: All methods in an interface are implicitly public and abstract.
3. Fields: Fields in an interface are implicitly public, static, and final.

Syntax Example:

interface Drawable {
void draw(); // Abstract method
}

Key Points
● Methods: Cannot have a body; must be implemented by classes.
● Fields: Can only be constants (i.e., static and final).
● Inheritance: A class can implement multiple interfaces.
● Default Methods: Interfaces can have default methods with a body, introduced in Java
8.

Examples

1. Basic Interface Implementation


interface Animal {
void makeSound();
}

class Dog implements Animal {


@Override
public void makeSound() {
System.out.println("Bark");
}
}

public class Test {


public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Bark
}
}

Output:

Bark

2. Interface with Default Method


interface Animal {
void makeSound();

default void eat() {


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

class Cat implements Animal {


@Override
public void makeSound() {
System.out.println("Meow");
}
}

public class Test {


public static void main(String[] args) {
Cat myCat = new Cat();
myCat.makeSound(); // Output: Meow
myCat.eat(); // Output: Eating...
}
}

Output:

Meow
Eating...
Inheritance in Java

Syntax
1. Class Inheritance: Use the extends keyword to inherit from a superclass.
2. Method Overriding: A subclass can override methods of the superclass using the
@Override annotation.

Syntax Example:

class Animal {
void eat() {
System.out.println("Eating...");
}
}

class Dog extends Animal {


@Override
void eat() {
System.out.println("Dog is eating...");
}
}

Key Points
● Single Inheritance: A class can inherit from only one superclass.
● Method Overriding: Allows a subclass to provide a specific implementation of a method
that is already defined in its superclass.
● Super Keyword: Used to access superclass methods and constructors.

Examples

1. Basic Inheritance
class Animal {
void makeSound() {
System.out.println("Some sound");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Bark");
}
}
public class Test {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Bark
}
}

Output:

Bark

2. Super Keyword Usage


class Animal {
void eat() {
System.out.println("Eating...");
}
}

class Dog extends Animal {


@Override
void eat() {
super.eat(); // Calling superclass method
System.out.println("Dog is eating...");
}
}

public class Test {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Output: Eating... Dog is eating...
}
}

Output:

Eating...
Dog is eating...

Interfaces and Inheritance Together


An important aspect of Java is how interfaces and inheritance can be used together. A class
can extend one class and implement multiple interfaces.

Example
interface Flyable {
void fly();
}

class Bird extends Animal implements Flyable {


@Override
public void fly() {
System.out.println("Flying...");
}

@Override
void makeSound() {
System.out.println("Tweet");
}
}

public class Test {


public static void main(String[] args) {
Bird myBird = new Bird();
myBird.makeSound(); // Output: Tweet
myBird.fly(); // Output: Flying...
}
}

Output:

Tweet
Flying...

Interfaces and inheritance are powerful features in Java that enable polymorphism and
abstraction. Interfaces allow classes to define a contract that must be fulfilled, while inheritance
facilitates code reuse and extension. Mastering both concepts will help in designing robust and
scalable object-oriented systems.

Do It Yourself
1. Create an interface Shape with an abstract method draw(). Implement this interface in
Circle and Square classes. Show how to create objects of these classes and call their
draw() methods.

2. Write a program with a superclass Vehicle and a subclass Car. The Car class should
override a method startEngine() from Vehicle. Demonstrate the usage of the Car
class.
3. Define two interfaces Readable and Writable with methods read() and write()
respectively. Create a class Document that implements both interfaces. Show how to
use this class to read from and write to a document.

4. Create a superclass Person with a method getName(). Derive a subclass Student


that overrides getName() and uses the super keyword to call the superclass method.
Display the results.

5. Write an interface Appliance with a default method turnOn(). Implement this


interface in Fan and Light classes. Display how these appliances are turned on using
the default method.

Quiz

1. What does an interface in Java define?


A) A set of classes
B) A set of methods without implementations
C) A set of fields and methods with implementations
D) A set of concrete methods

Answer: B) A set of methods without implementations

2. Which keyword is used to implement an interface in Java?


A) implements
B) extends
C) interface
D) abstract

Answer: A) implements

3. Given the following code, what will be the output?

interface A {
void display();
}

class B implements A {
public void display() {
System.out.println("Display from B");
}
}

public class Test {


public static void main(String[] args) {
A obj = new B();
obj.display();
}
}
A) Compilation error
B) Runtime error
C) Display from B
D) No output

Answer: C) Display from B

4. Which of the following statements is true about class inheritance in Java?


A) A class can extend multiple classes
B) A class can implement multiple interfaces
C) A class can implement multiple classes
D) A class cannot extend any other class

Answer: B) A class can implement multiple interfaces

5. What is the purpose of the super keyword in Java?


A) To access the superclass constructor
B) To access the superclass methods and fields
C) To call the subclass methods
D) To create a new superclass

Answer: B) To access the superclass methods and fields

References
End of Session - 18

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