0% found this document useful (0 votes)
0 views

OOPs_Module_2

This document covers the fundamentals of inheritance, packaging, and interface integration in Java as part of an Object-Oriented Programming course. It explains key concepts such as single, multilevel, and hierarchical inheritance, along with the use of access modifiers and the 'super' keyword. Additionally, it includes examples and problem statements to illustrate the application of these concepts in Java programming.

Uploaded by

Vinay Adari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

OOPs_Module_2

This document covers the fundamentals of inheritance, packaging, and interface integration in Java as part of an Object-Oriented Programming course. It explains key concepts such as single, multilevel, and hierarchical inheritance, along with the use of access modifiers and the 'super' keyword. Additionally, it includes examples and problem statements to illustrate the application of these concepts in Java programming.

Uploaded by

Vinay Adari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

OBJECT-ORIENTED PROGRAMMING 22CSE43

MODULE 2
Java's Building Blocks: Inheritance, Packaging, and
Interface Integration

SYLLABUS:
Inheritance: Basics, using super, Creating multilevel hierarchy, When constructors
are called, Method Overriding, Applying method overriding, Using abstract classes,
Using final with inheritance, The object class.
Packages and Interfaces: Defining a package, finding packages and CLASSPATH, A
short package example, Access protection, Importing packages, Defining an
interface, Implementing interfaces, Nested interfaces, Applying interfaces,
Variables in interfaces.

Inheritance

Inheritance in Java is a fundamental concept of Object-Oriented Programming (OOP) that


allows a class to inherit properties and behaviors (methods) from another class. The class that
inherits is called the subclass or child class, and the class being inherited from is called the
superclass or parent class..

Question: Why Do We Need Java Inheritance?

• The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes.
• When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
• Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.

Page 1 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Important Terminologies Used in Java Inheritance

• Class: Class is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. Class is not a real-world entity. It is just a template
or blueprint or prototype from which objects are created.
• Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).
• Sub Class/Child Class: The class that inherits the other class is known as a
subclass(or a derived class, extended class, or child class). The subclass can add its
own fields and methods in addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want
to create a new class and there is already a class that includes some of the code that
we want, we can derive our new class from the existing class. By doing this, we
are reusing the fields and methods of the existing class.
How to Use Inheritance in Java?

The general form of a class declaration that inherits a superclass is shown here:

class subclass-name extends superclass-name {

// body of class

You can only specify one superclass for any subclass that you create. Java does not
support the inheritance of multiple superclasses into a single subclass.

Page 2 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Syntax:
class superclass
{
// superclass data variables
// superclass member functions
}
class subclass extends superclass
{
// subclass data variables
// subclass member functions
}

Extends keyword in Java

The ‘extends’ keyword extends a class and is an indicator that a class is being inherited by
another class. When you say class B extends a class A, it means that class B is inheriting the
properties(methods, attributes) from class A. Here, class A is the superclass or parent class
and class B is the subclass or child class.
AN EXAMPLE:
class Employee{

float salary=40000;

class Programmer extends Employee{

int bonus=10000;

public static void main(String args[]){

Programmer p=new Programmer();

System.out.println("Programmer salary is:"+p.salary);

System.out.println("Bonus of Programmer is:"+p.bonus);

}
Page 3 of 52
}
OBJECT-ORIENTED PROGRAMMING 22CSE43

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){ Dog
d=new Dog();
d.bark();
d.eat();
}}
Output:
Barking….
Eating…..

Page 4 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Example Program:
Create a class named Person with the following characteristics:
• A String variable name.
• A method inputName() that takes user input for the name.
• A method displayName() that prints the name to the console.
Create a class named Citizen that inherits from Person and has the following characteristics:
• An int variable age.
• A method inputAge() that takes user input for the age.
• A method displayAge() that prints the age to the console.
import java.util.Scanner;
// Superclass Person
class Person {
String name;
void inputName() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
name = sc.nextLine();
}
void displayName() {
System.out.println("Name: " + name);
}
}
// Subclass Citizen inheriting from Person
class Citizen extends Person {
int age;
void inputAge() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter age: ");

Page 5 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

age = sc.nextInt();
}
void displayAge() {
System.out.println("Age: " + age);
}
}
// Main class to test the functionality
public class Main {
public static void main(String[] args) {
Citizen c = new Citizen();
c.inputName();
c.inputAge();
c.displayName();
c.displayAge();
}
}
Multilevel Inheritance
In Multi-Level Inheritance in Java, a class extends to another class that is already extended
from another class.
For example, if there is a class A that extends class B and class B extends from another class
C, then this scenario is known to follow Multi-level Inheritance.
Consider three classes, class Vehicle, class Car, and class SUV. Here, the class Vehicle is the
grandfather class. The class Car extends class Vehicle and the class SUV extends class Car.
Consider three classes – Car, Maruti and Maruti800. We have done a setup – class Maruti
extends Car and class Maruti800 extends Maruti. With the help of this Multilevel hierarchy
setup our Maruti800 class is able to use the methods of both the classes (Car and Maruti).
Example:
class Animal{

Page 6 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){ BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Hierarchical Inheritance

When two or more classes are inherited from a single class, it is known as hierarchical
inheritance

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{

Page 7 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

public static void main(String args[]){


Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}
Output:
meowing...
eating...
Why multiple inheritance is not supported in java?

• Java does not support multiple inheritance with classes to avoid ambiguity, complexity,
and the diamond problem. However, Java allows multiple inheritance through
interfaces.

1. Diamond Problem (Method Ambiguity)

• If multiple parent classes have the same method and a child class inherits from both,
which method should be executed?

Page 8 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

The compiler gets confused about whether to call the msg() method of class A or class B. This
is the ambiguity problem faced by the compiler hence multiple inheritance is not supported
in Java.

2. Complexity in Constructor Calls


If Java allowed multiple inheritance, a child class would inherit from multiple parent classes.
But which parent's constructor should be called first?
3. Code Maintenance Issues
If multiple classes define the same method, accidental overrides can introduce bugs.
Resolving conflicts in large projects would make code harder to manage.
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.

Member Access and Inheritance

In java, the access modifiers define the accessibility of the class and its members. For example,
private members are accessible within the same class members only. Java has four access
modifiers, and they are default, private, protected, and public.

In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The class
acts as a container of data and methods. So, the access modifier decides theaccessibility of class
members across the different packages.

In java, the accessibility of the members of a class or interface depends on its access specifiers.
The following table provides information about the visibility of both data members and
methods.

Page 9 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Example Program:
// Parent class demonstrating access specifiers
class Person {
public String name = "John"; // Public - accessible everywhere
private int age = 30; // Private - accessible only in this class
protected String city = "New York"; // Protected - accessible in subclasses
String country = "USA"; // Default - accessible within the same package
}
// Subclass inheriting from Person
class Employee extends Person {
void showDetails() {
System.out.println("Accessing Parent Class Members from Subclass:");
System.out.println("Name (public): " + name); // Allowed
// System.out.println("Age (private): " + age); // Not allowed (private)
System.out.println("City (protected): " + city); // Allowed (protected)
System.out.println("Country (default): " + country); // Allowed (default)
}
}
public class AccessSpecifierDemo {
public static void main(String[] args) {
Page 10 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Employee emp = new Employee();


emp.showDetails();
}
Accessing Private Data Members:
The derived class can inherit only those data members and methods of parent class, that are
declared as public or protected.
• If the members or methods of super class are declared as private then the derived
class cannot access them.
• The private members can be accessed only in its own class.
• Such private members can only be accessed using public or protected getter and setter
methods of super class.
// Superclass
class Parent {
private String name;
// Setter method to set the private variable
public void setName(String name) {
this.name = name;
}
// Getter method to retrieve the private variable
public String getName() {
return name;
}
}
// Subclass
class Child extends Parent {
public void display() {
System.out.println("Accessing private member using getter: " + getName());
}
}

Page 11 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

// Main class
public class Main {
public static void main(String[] args) {
Child obj = new Child();

// Using setter to assign value to private variable


obj.setName("John Doe");

// Using getter to access the private variable


obj.display();
}
}

SUPER KEYWORD IN JAVA


The super keyword refers to superclass (parent) objects.
It is used to call superclass methods, and to access the superclass constructor.
The use of super keyword
1) To access the data members of parent class when both parent and child class have
member with same name
2) To explicitly call the no-arg and parameterized constructor of parent class
3) To access the method of parent class when child class has overridden that method.
How to use super keyword to access the variables of parent class
If a subclass has a variable with the same name as the superclass, super.variableName is used to
access the super class variable.
class Superclass
{
int num = 100;
}
class Subclass extends Superclass
Page 12 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

{
int num = 110;
void printNumber(){
System.out.println(“Super class Nmuber:”+super.num);
System.out.println(“Sub class Nmuber:”+num);
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printNumber();
}
}
Calling the Parent Class Constructor using super()
• super(parameters) is used inside a subclass constructor to call the parameterized
constructor of the parent class.
• It must be the first statement inside the subclass constructor.
Syntax: super(parameters);
class Parent {
//Parent class constructor
Parent(parameters) {
// Initialization of superclass attributes
}
}
class Child extends Parent {
// Subclass constructor
Child(parameters) {
super(parameters); // Calls the parent class constructor
// Initialization of subclass attributes
}
}

Page 13 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Example Program:
class Superclass {
int x;
Superclass(int x) {
this.x = x;
}
}
class Subclass extends Superclass {
int y;
Subclass(int x, int y) {
super(x); // calling superclass constructor
this.y = y;
}
}
public class Main {
public static void main(String[] args) {
Subclass obj = new Subclass(10, 20);
System.out.println("x: " + obj.x);
System.out.println("y: " + obj.y);
}
}
Accessing Parent Class Methods using super keyword(super.methodName())
➢ super.methodName() is used to call a method of the parent class when it is overridden
in the subclass.
➢ When a child class declares a same method which is already present in the parent class
then this is called method overriding.
➢ When a child class overrides a method of parent class, then the call to the method from
child class object always call the child class version of the method.

Page 14 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

➢ However by using super keyword like this: super.method_name() you can call the
method of parent class.
Example Program:
class Parentclass {
void display() {
System.out.println("Parent class method");
}
}
class Subclass extends Parentclass {
void display() {
System.out.println("Child class method");
}
void printMsg() {
display(); // This would call the Sub class method
super.display(); // This would call the Super class method
}
public static void main(String args[]) {
Subclass obj = new Subclass();
obj.printMsg();
}
}
Problem Statement:
Design a Java program using classes to model a shipment box system with multilevel
inheritance. Implement classes Box, BoxWeight, and Shipment to represent different aspects
of a shipment box. The Box class represents basic dimensions, BoxWeight extends Box to
include weight, and Shipment extends BoxWeight to include shipment cost.
Write a Java program that includes:
Box Class:
• Private attributes width, height, and depth.

Page 15 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

• Constructor Box(double width, double height, double depth) to initialize these


attributes.
• Method double volume() to calculate and return the volume of the box.
BoxWeight Class (Subclass of Box):
• Inherits from Box and adds a private attribute weight.
• Constructor BoxWeight(double width, double height, double depth, double weight) to
initialize dimensions using super() and set the weight.
• Method double getWeight() to return the weight of the box.
Shipment Class (Subclass of BoxWeight):
• Inherits from BoxWeight and adds a private attribute cost.
• Constructor Shipment(double width, double height, double depth, double weight,
double cost) to initialize dimensions, weight using super(), and set the cost.
• Method double getCost() to return the shipment cost.
// Box class - base class
class Box {
private double width;
private double height;
private double depth;
// Constructor
public Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
// Method to calculate volume
public double volume() {
return width * height * depth;
}
}

Page 16 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

// BoxWeight class - subclass of Box


class BoxWeight extends Box {
private double weight;
// Constructor
public BoxWeight(double width, double height, double depth, double weight) {
super(width, height, depth); // Call superclass constructor
this.weight = weight;
}
// Method to return weight
public double getWeight() {
return weight;
}
}
// Shipment class - subclass of BoxWeight
class Shipment extends BoxWeight {
private double cost;
// Constructor
public Shipment(double width, double height, double depth, double weight, double cost) {
super(width, height, depth, weight); // Call superclass constructor
this.cost = cost;
}
// Method to return shipment cost
public double getCost() {
return cost;
}
}
// Main class to test the hierarchy
public class Main {
public static void main(String[] args) {

Page 17 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Shipment shipment = new Shipment(10.0, 5.0, 2.0, 4.5, 150.75);


System.out.println("Volume of the box: " + shipment.volume());
System.out.println("Weight of the box: " + shipment.getWeight());
System.out.println("Shipment cost: " + shipment.getCost());
}
}

When constructors are called:

 A constructor is a block of code used to initialize an object. It is called when an object


of a class is created.
 In inheritance, a subclass inherits the properties and methods of its superclass.
 The superclass constructor is always invoked when a subclass object is created.
 In Java, when a subclass object is created, the parent class constructor is called first,
followed by the child class constructor.
 The superclass constructor is called either explicitly using super() or implicitly.
Example Program:
class Parent {
Parent() {
System.out.println("Parent Constructor Called");
}
}
class Child extends Parent {
Child() {
super(); //Explicit call to the superclass constructor.
//Implicitly it will call parent class constructor without super() also.
System.out.println("Child Constructor Called");
}
}
public class Main {

Page 18 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

public static void main(String[] args) {


Child obj = new Child(); // Creating object of Child class
}
}
Output:
Parent Constructor Called
Child Constructor Called
Constructor Calling in Multilevel Inheritance
• If there are multiple levels of inheritance, Java calls constructors from top to bottom.
class A {
A() {
System.out.println("Constructor of A");
}
}
class B extends A {
B() {
System.out.println("Constructor of B");
}
}
class C extends B {
C() {
System.out.println("Constructor of C");
}
}
public class Main {
public static void main(String[] args) {
C obj = new C(); // Object creation
}
}

Page 19 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Output:
Constructor of A
Constructor of B
Constructor of C
Explanation:
• The object of C is created.
• Java first calls A's constructor, then B's constructor, and finally C's constructor.
METHOD OVERRIDING
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
Overriding is done so that a child class can give its own implementation to a method which
is already provided by the parent class.
In this case the method in parent class is called overridden method and the method in child
class is called overriding method.
Method overriding is used for runtime polymorphism.

Java Method Overriding Rules


• Same Method Signature: Both the superclass and the subclass must have the same
method name, the same return type and the same parameter list.
• Inheritance Required – The child class must inherit from the parent class to override
its method.
• We Cannot Override final Methods – A method declared as final in the parent class

Page 20 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

cannot be overridden.
• We Cannot Override Static Methods – Static methods belong to the class, not
instances, so they cannot be overridden.
• Access Modifiers – The overridden method in the child class cannot have a more
restrictive access modifier than the parent class method.
Example: If the parent method is protected, the overridden method cannot be private.
• super Keyword – The super keyword can be used in the child class to call the
overridden method of the parent class.
• We should always override abstract methods of the superclass
Applying method overriding
Different banks offer different interest rates for savings accounts. The base class Bank
provides a general method to return the interest rate, and each specific bank overrides
this method to provide its own interest rate.
class Bank {
double getInterestRate() {
return 0.0; // Default interest rate
}
}
class SBI extends Bank {
@Override
double getInterestRate() {
return 4.5; // SBI interest rate
}
}
class HDFC extends Bank {
@Override
double getInterestRate() {
return 5.0; // HDFC interest rate

Page 21 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

}
}
class ICICI extends Bank {
@Override
double getInterestRate() {
return 5.5; // ICICI interest rate
}
}
public class Main {
public static void main(String[] args) {
Bank sbi = new SBI();
Bank hdfc = new HDFC();
Bank icici = new ICICI();
System.out.println("SBI Bank Interest Rate: " + sbi.getInterestRate() + "%");
System.out.println("HDFC Bank Interest Rate: " + hdfc.getInterestRate() + "%");
System.out.println("ICICI Bank Interest Rate: " + icici.getInterestRate() + "%");
}}
Note:
The @Override annotation in Java is used to indicate that a method in a subclass is overriding
a method from its superclass. It helps to prevent errors and improve code readability.
What Happens If We Do Not Use Method Overriding?

• If method overriding is not used, the superclass method will be called instead
of the subclass method.
Example without overriding:

Animal myDog = new Dog();

myDog.sound(); // Output: Animal makes a sound

Without overriding, the output would be from the Animal class, not the Dog class.

Page 22 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Limitations of Method Overriding:

1. Cannot override static methods – Static methods belong to the class, not
the object, so they cannot be overridden.
2. Cannot override final methods – A method declared as final in the
superclass cannot be overridden.
3. Constructor cannot be overridden – Constructors are not inherited, so
they cannot be overridden.
4. Access modifier constraint – An overridden method in the subclass cannot
have a more restrictive access modifier than the superclass method.

Question: Can we override static methods? Can the main() method be


overridden?

No, we cannot override static methods in Java.

Reason:

• Static methods are associated with the class rather than the object.

• Method overriding is based on dynamic (runtime) polymorphism where the method


call is resolved at runtime using the object’s reference.

• Since static methods are resolved at compile time (using static binding), they cannot
participate in method overriding.

The main() method cannot be overridden because:

1. The main() method is static, and static methods cannot be overridden.

2. However, you can define a main() method in the subclass — but this is called method
hiding (not overriding).
Dynamic method dispatch

◾ Dynamic method dispatch is the mechanism by which a call to an overridden method

Page 23 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

is resolved at run time, rather than compile time. Dynamic method dispatch is
important because this is how Java implements run-time polymorphism.

◾ A superclass reference variable can refer to a subclass object. Java uses this fact to
resolve calls to overridden methods at run time. Here is how. When an overridden
method is called through a superclass reference, Java determines which version of that
method to execute based upon the type of the object being referred to at the time the call
occurs. Thus, this determination is made at run time.
Example Program:
// Dynamic Method Dispatch
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
//override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme() void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
Page 24 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

C c = new C(); // object of type C


A r; // obtain a reference of
type A r = a; // r refers to an
A object
r.callme(); // calls A's version of
callme r = b; // r refers to a B
object
r.callme(); // calls B's version of
callme r = c; // r refers to a C
object
r.callme(); // calls C's version of callme
}
}
OUTPUT:
◾ Inside A’s callme method
◾ Inside B’s callme method
◾ Inside C’s callme method
Using abstract classes:
 A class which is declared with the abstract keyword is known as an abstract class
in Java.
 It can have abstract and non-abstract methods (method with the body).
 Abstraction lets you focus on what the object does instead of how it does it.
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Points to remember for ABSTRACT CLASS
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.

Page 25 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

• It can have constructors and static methods also.


• It can have final methods which will force the subclass not to change the body of the
method.
Syntax of Abstract Class:
abstract class ClassName {
// Abstract method (without body)
abstract void abstractMethod();
// Concrete method (with body)
void concreteMethod() {
System.out.println("This is a concrete method.");
}
}
Example:
abstract class A{ //abstract class
abstract void printStatus();//no method body and abstract //abstract method
}
Example Program:
//abstract parent class
abstract class Animal{
//abstract method
public abstract void sound();
}
//Dog class extends Animal class
class Dog extends Animal{
// Implementing the abstract method
public void sound(){
System.out.println("Woof");
}
}

Page 26 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

class Cat extends Animal {


// Implementing the abstract method
void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
// Creating objects of concrete subclasses
Dog dog = new Dog();
Cat cat = new Cat();
// Calling the makeSound method
dog.makeSound();
cat.makeSound();
}
}
Explanation:
Since the animal sound differs from one animal to another, there is no point to implement
this method in parent class. This is because every child class must override this method to
give its own implementation details, like Lion class will say “Roar” in this method
and Dog class will say “Woof”. Thus, making this method abstract would be the good choice
as by making this method abstract we force all the sub classes to implement this method(
otherwise you will get compilation error), also we need not to give any implementation to
this method in parent class.
Since the Animal class has an abstract method, you must need to declare this class abstract.
Now each animal must have a sound, by making this method abstract we made it
compulsory to the child class to give implementation details to this method.

Page 27 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Example Program2:
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In real scenario, object is provided through method, e.g., getShape(
) method
s.draw();
}
}
Using final with inheritance

In Java, the final keyword is used to denote constants. Final keyword can be used with
• Variables
• Methods
• Classes.
Once any entity (variable, method or class) is declared final, it can be assigned only once. That
is,
1. The final variable cannot be reinitialized with another value
2. The final method cannot be overridden

Page 28 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

3. The final class cannot be extended


1) final variable

• If you make any variable as final, you cannot change the value of final variable(It will
be constant).
class Main {
public static void main(String[] args) {
// create a final variable
final int AGE = 32;
// try to change the final variable
AGE = 45;
System.out.println("Age: " + AGE);
}
}
In the above program, we have created a final variable named age. And we have tried to change
the value of the final variable.
• When we run the program, we will get a compilation error with the following message.
Can’t assign a value to a final variable AGE, AGE=45.
2. Java final Method
In Java, the final method cannot be overridden by the child class.
class FinalDemo {
// create a final method
public final void display() {
System.out.println("This is a final method.");
}
}
class Main extends FinalDemo {
// try to override final method
@override
public final void display() {
Page 29 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

System.out.println("The final method is overridden.");


}
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}
Output: Compile Time Error
display() in Main cann’t override display() in FinalDemo
If you make any class as final, you cannot extend it.

3. Java final Class


• In Java, the final class cannot be inherited by another class.
// create a final class
final class FinalClass {
public void display() {
System.out.println("This is a final method.");
}
}
// try to extend the final class
class Main extends FinalClass {
public void display() {
System.out.println("The final method is overridden.");
}
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}
When we run the program, we will get a compilation error with the following message.
Page 30 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Can’t inherit from final FinalClass.


Packages:
A java package is a group of similar types of classes, interfaces and sub-packages.
In java we use packages to organize our classes and interfaces.

Advantages of using a package in Java


• Reusability: While developing a project in java, we often feel that there are few things
that we are writing again and again in our code. Using packages, you can create such
things in form of classes inside a package and whenever you need to perform that same
task, just import that package and use the class.
• Better Organization: Again, in large java projects where we have several hundreds of
classes, it is always required to group the similar types of classes in a meaningful
package name so that you can organize your project better and when you need
something you can quickly locate it and use it, which improves the efficiency.
• Avoids Naming Conflicts: We can define two classes with the same name in different
packages so to avoid name collision, we can use packages.
Types of packages:
There are two types of packages in Java:
1. Built-in Packages: These are predefined packages provided by Java that come along
with JDK.
Some of the commonly used built-in packages are:

Page 31 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Package Name Description

Provides fundamental classes such as String, Math, Integer, etc.


java.lang
(Automatically imported)

java.util Contains utility classes such as ArrayList, HashMap, Collections, etc.

Provides classes for input and output operations like File,


java.io
BufferedReader, etc.

java.net Supports networking operations like Socket, URL, etc.

Contains classes for database connectivity such as Connection,


java.sql
Statement, etc.

javax.swing Provides GUI components like JFrame, JButton, etc.

2.User-defined Packages: These are packages created by the user to organize related classes
and interfaces.
User-defined packages can also be imported into other classes & used exactly in the same way
as the Built- in packages.
Creating User Defined Packages
Syntax :
package packageName;
public class className
{
// Body of className
}

Page 32 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

We must first declare the name of the package using the package keyword followed by the
package name. This must be the first statement in a Java source file. Then define a class as
normally.
To create a user-defined package, use the package keyword:
// Define a package
package mypackage;
public class MyPackageClass {
public void displayMessage() {
System.out.println("Hello from MyPackageClass inside mypackage!");
}
}
Explanation:
package mypackage;---→This line declares that this class belongs to a package named
mypackage.
• It must be the first statement in the Java file (except comments).
When compiled, the class file will be stored in a folder named mypack.
How to Compile and Run?
Step 1: Save the File
Save the program as MyPackageClass.java inside a folder.
Step 2: Compile the Program
Use the -d option to place the .class file inside the package directory
Syntax:
1. javac -d directory javafilename.java
-d directory → Specifies the destination directory where compiled .class files should be stored.
When you use the -d directory option while compiling a Java file that contains a package
declaration, the compiler will:
1. Create the package folder inside the specified directory (if it doesn't already
exist).
2. Store the compiled .class file inside that package folder.

Page 33 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

2. javac -d . javafilename.java
• The dot (.) means the current directory.
-d . → . (dot) means the current directory will be used for placing the package folder.
• It will keep the package within the same directory, i.e. a mypack folder is created in the
current directory, and MyPackageClass.class is stored inside it.
Step 3: Run the Program
Navigate to the folder containing mypack and execute:
java mypack.MyPackageClass
How to use the user-defined package
create another Java file in the same directory to import and use the class from the package.
// Import the user-defined package
import mypackage.MyPackageClass;
public class MainClass {
public static void main(String[] args) {
MyPackageClass obj = new MyPackageClass();
obj.displayMessage();
}
}
Finding packages and CLASSPATH
When you compile or run a Java program that uses a package, Java needs to know where to
find the class files. This is handled using the CLASSPATH.
What is CLASSPATH in Java?
• CLASSPATH is an environment variable or command-line option that tells the Java
compiler (javac) and Java Virtual Machine (java) where to look for user-defined
classes and packages.
The Java runtime system searches for packages in three locations
1. Current folder
By default, Java looks in the current directory (.) if the CLASSPATH is not set.

Page 34 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

• First, the Java run-time system uses the current working directory as its starting
point.
• If your package is in a subdirectory of the current directory, it will be found.
2. -classpath
• Second, you can use the -classpath or –cp option with java and javac to specify
the path to your classes.
• Suppose mypackage is stored elsewhere, like:
C:/java_packages/mypackage/MyPackageClass.class
Then you can use the -cp (or -classpath) option to point Java to the location:
javac -cp C:/java_packages MainClass.java
java -cp .;C:/java_packages MainClass
3. Setting CLASSPATH Permanently in Java
The CLASSPATH environment variable in Java tells the Java Compiler (javac) and Java
Virtual Machine (java) where to find class files, external libraries (JAR files), and packages.
If you don’t want to specify the -cp (or -classpath) option every time you compile or run a
Java program, you can set CLASSPATH permanently.
Example: Using CLASSPATH for Java Compilation & Execution
Project Structure
C:/java_projects/
│── mypackage/
│ ├── MyPackageClass.java
│ ├── MyPackageClass.class

│── MainClass.java
│── MainClass.class
│── lib/
│ ├── myLibrary.jar
Set CLASSPATH Permanently
Set CLASSPATH=C:\java_projects;C:\java_projects\lib\myLibrary.jar;

Page 35 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Compile & Run Without -cp


javac MainClass.java
Execution
java MainClass
No need to manually specify -cp because CLASSPATH is already set!

Access Protection in Java Packages


• In java, the access modifiers define the accessibility of the class and its members. For
example, private members are accessible within the same class members only.
• Java has four access modifiers, and they are default, private, protected, and public.
• In java, the package is a container of classes, sub-classes, interfaces, and sub-packages.
The class acts as a container of data and methods. So, the access modifier decides the
accessibility of class members across the different packages.
• In java, the accessibility of the members of a class or interface depends on its access
specifiers. The following table provides information about the visibility of both data
members and methods.

Page 36 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Importing packages in Java:


Java has an import statement that allows you to import an entire package or use only certain
classes and interfaces defined in the package.
The general form of import statement is:
1. Import a Single Class
import package.name.ClassName; //To import a certain class only
Example:
import java.util.Scanner; // imports only Scanner class
2. Import All Classes from a Package
import package.name.*; // To import the whole package
Example:
import java.util.*; // imports everything inside java.util package
3.Importing classes using Fully Qualified Name in Java
In Java, you can access classes from packages without importing them by using their fully
qualified name (FQN).
A Fully Qualified Name (FQN) includes the package name + class name.
Syntax:
package_name.ClassName objectName = new package_name.ClassName();
Example:
without using import, we can use the fully qualified name:
java.util.Scanner sc = new java.util.Scanner(System.in);

Defining an interface:

 An interface in Java is a blueprint of a class that contains static constants and abstract
methods.
 There can be only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java.
 In other words, you can say that interfaces can have abstract methods and variables. It

Page 37 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

cannot have a method body.


 Java Interface also represents the IS-A relationship.
 Interfaces are used to specify what a class must do, but not how it does it.
 The class that implements interface must implement all the methods of that interface.
Also, java programming language does not allow you to extend more than one class,
However you can implement more than one interfaces in your class.
 In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
Key Features of Interfaces:
1. All methods are public and abstract by default (unless declared as default or static).
2. Variables in interfaces are implicitly public, static, and final (constants).
3. Since Java 8, we can have default and static methods in an interface.
4. Since Java 9, we can have private methods in an interface.
5. Multiple interfaces can be implemented by a class, enabling multiple inheritance of
type.
6. Interfaces cannot have constructors because they cannot be instantiated directly.

Page 38 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

An interface is declared by using the interface keyword.

Syntax:

interface InterfaceName {
// Constant (public static final by default)
DataType CONSTANT_NAME = value;
// Abstract method (public and abstract by default)
ReturnType methodName(Parameters);
// Default method (Java 8+)
default ReturnType defaultMethodName(Parameters) {
// method body
}
// Static method (Java 8+)
static ReturnType staticMethodName(Parameters) {
// method body
}
}
Example:
interface Animal {
// final constant variable
int LEGS = 4; // public static final by default
void makeSound(); // public and abstract by default
}
Note:
Interface fields are public, static and final by default, and the methods are public and abstract.
In Java (since Java 8), interfaces can contain default methods — methods that have a body
(i.e., implementation).
Now imagine this:
• You have an interface with many classes implementing it.

Page 39 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

• Later, you want to add a new method to the interface.


• Without default methods, all implementing classes would break because they must
now implement the new method!
Default methods solve this!
• They let you add new methods to interfaces with default implementations, so
existing classes continue to work without changes.
• For example, in a payment system, if you have a PaymentGateway interface
implemented by several payment methods like credit card, upi payment and PayPal.
Now, you want to add logging to track every payment. So, you add a new method
logTransaction() as a default method. allows all existing implementations to inherit it
automatically without requiring code changes.
• Now, all classes automatically get logTransaction() — and they don’t break
Implementing Interfaces

• Once an interface has been defined, one or more classes can implement that interface.
• To implement an interface, include the implements clause in a class definition, and then
implement the methods defined by the interface.
The general form of a class that includes the implements clause looks like this:
Access_specifier class classname [extends superclass] [implements interface [,interface...]] {
// class-body
}
• Here, access_specifier is either public or not used. If a class implements more than one
interface, the interfaces are separated with a comma.
If a class implements two interfaces that declare the same method, then the same method will
be used by clients of either interface.
• The methods that implement an interface must be declared public. Also, the type signature
of the implementing method must match exactly the type signature specified in the interface
definition.
Real-World Scenario for Interface in Java:

Page 40 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Scenario: Payment System


Imagine you're building an payment processing module for an e-commerce platform. The
platform should be able to handle multiple payment methods like:
• Credit Card
• PayPal
• UPI
Each payment method will process payment differently, but they all must support a pay()
method.
To achieve this, define a common interface named Payment with a method pay(double
amount). Then, create concrete classes that implement this interface for different payment
modes such as:
CreditCardPayment
PayPalPayment
UpiPayment
Program:
//Interface
interface Payment {
void pay(double amount);
}
//Implementing Classes:
class CreditCardPayment implements Payment {
public void pay(double amount) {
System.out.println("Paid ₹" + amount + " using Credit Card.");
}
}
class PayPalPayment implements Payment {
public void pay(double amount) {
System.out.println("Paid ₹" + amount + " using PayPal.");
}

Page 41 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

}
class UpiPayment implements Payment {
public void pay(double amount) {
System.out.println("Paid ₹" + amount + " using UPI.");
}
}
//Usage in Application:
public class PaymentApp {
public static void main(String[] args) {
Payment payment;
payment = new CreditCardPayment();
payment.pay(1000.00);
payment = new PayPalPayment();
payment.pay(750.50);
payment = new UpiPayment();
payment.pay(300.00);
}
}
Example Program 2:
You are working on a utility to transform numbers. Create an interface
named NumberTransformer with a method transform() responsible for transforming and
displaying the given number.
• Implement classes SquareTransformer and CubeTransformer that implement
the NumberTransformer interface.
• SquareTransformer should transform and display the square of the input number,
and CubeTransformer should transform and display the cube of the input number.
// Interface definition
interface NumberTransformer {
void transform(int number); // method to transform and display the number

Page 42 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

}
// Class to calculate square of the number
class SquareTransformer implements NumberTransformer {
public void transform(int number) {
int result = number * number;
System.out.println("Square of " + number + " is: " + result);
}
}
// Class to calculate cube of the number
class CubeTransformer implements NumberTransformer {
public void transform(int number) {
int result = number * number * number;
System.out.println("Cube of " + number + " is: " + result);
}
}
// Main class to test the implementation
public class Main {
public static void main(String[] args) {
NumberTransformer square = new SquareTransformer();
NumberTransformer cube = new CubeTransformer();
int input = 5;
square.transform(input); // Output: Square of 5 is: 25
cube.transform(input); // Output: Cube of 5 is: 125
}
}
The relationship between classes and interfaces

 As shown in the figure given below, a class extends another class,


 an interface extends another interface, but a class implements an interface.

Page 43 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Example 1:
interface printable
{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}
Example 2:
interface Drawable{
void draw();
}

Page 44 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

//Implementation: by second user


class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}
}
Example 3:
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}

Page 45 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Multiple inheritance in Java by interface


• Multiple inheritance means a class can inherit features from more than one parent
(superclass or interface).
• In Java, multiple inheritance with classes is not allowed to avoid ambiguity
problems (like the Diamond Problem), but Java does support multiple inheritance
through interfaces.
• If a class implements multiple interfaces, or an interface extends multiple interfaces, it
is known as multiple inheritance.

Example:
interface Printable{
void print();
}
interface Showable{
void show();
}

Page 46 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

class A7 implements Printable,Showable{


public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Problem Statement 2:
Imagine you are building a system for a Smart Home. Devices like Smart Speakers need to:
• Play music
• Connect to the internet
• Respond to voice commands
• Each of these functionalities can be defined in separate interfaces, and a Smart
Speaker can implement all of them.
// Interface for music-playing capability
interface MusicPlayer {
void playMusic(String song);
}
// Interface for internet connectivity
interface InternetEnabled {
void connectToWifi(String networkName);
}
// Interface for voice command response
interface VoiceAssistant {
void respondToCommand(String command);
}

Page 47 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

// SmartSpeaker class implementing all three interfaces


class SmartSpeaker implements MusicPlayer, InternetEnabled, VoiceAssistant {
public void playMusic(String song) {
System.out.println("Playing music: " + song);
}
public void connectToWifi(String networkName) {
System.out.println("Connected to Wi-Fi: " + networkName);
}
public void respondToCommand(String command) {
System.out.println("Responding to voice command: " + command);
}
}
// Main class to test the SmartSpeaker functionality
public class SmartHomeSystem {
public static void main(String[] args) {
SmartSpeaker speaker = new SmartSpeaker();
speaker.connectToWifi("Home_Network");
speaker.playMusic("Imagine - John Lennon");
speaker.respondToCommand("What's the weather like?");
}
}
Nested Interfaces:
 An interface declared within another interface or class, is known as a nested interface.
 The nested interfaces are used to group related interfaces so that they can be easy to
maintain.
 The nested interface must be referred to by the outer interface or class.
 It can't be accessed directly.
Example:

Page 48 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public static void main(String args[])
{
Showable.Message message=new TestNestedInterface1();//upcasting here
message.msg();
}
}
Variables in interface:
 In Java, an interface variable is implicitly public, static, and final.
 This means that the variable's value cannot be changed once it is assigned.
 Furthermore, interface variables are accessible to all implementing classes, promoting
code reusability and standardization.
public interface Constants {
String DATABASE_URL = "jdbc:mysql://localhost:3306/mydatabase";
String USERNAME = "root";
String PASSWORD = "password123";
}
public class DatabaseConnection {

Page 49 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

// Code for establishing a database connection using the constants


}
Example:
public interface Currency {
String SYMBOL = "$";
double convertToUSD(double amount);
}
public class Dollar implements Currency {
public double convertToUSD(double amount) {
return amount;
}
}
public class Euro implements Currency {
public double convertToUSD(double amount) {
return amount * 1.18;
}
}
public class Main
{
public static void main(String[] args)
{
Currency dollar = new Dollar();
Currency euro = new Euro();
double amount = 100;
System.out.println("Amount in dollars: " + dollar.convertToUSD(amount) + SYMBOL);
System.out.println("Amount in euros: " + euro.convertToUSD(amount) + SYMBOL);
}
}

Page 50 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

The object class:


 The Object class is the parent class of all the classes in java by default. In other words,
it is the topmost class of java.
 The Object class is beneficial if you want to refer any object whose type you don't know.
Say that parent class reference variable can refer the child class object, know as
upcasting.
 The Object class provides some common behaviors to all the objects such as object can
be compared, object can be cloned, object can be notified etc.
Example:
If there is getObject() method that returns an object but it can be of any type like
Employee,Student etc, we can use Object class reference to refer that object.
For example:
Object obj=getObject();//we don't know what object will be returned
 The Object class provides some common behaviors to all the objects such as object can
be compared, object can be cloned, object can be notified etc.
Cloning
 The object cloning is a way to create exact copy of an object.
 The clone() method of Object class is used to clone an object.
 The java.lang.Cloneable interface must be implemented by the class whose object
clone we want to create.
 If we don't implement Cloneable interface, clone() method
generates CloneNotSupportedException.
 The clone() method is defined in the Object class.
Syntax of the clone() method is as follows:
protected Object clone() throws CloneNotSupportedException
Example:
class Student18 implements Cloneable{
int rollno;
String name;

Page 51 of 52
OBJECT-ORIENTED PROGRAMMING 22CSE43

Student18(int rollno,String name)


{
this.rollno=rollno;
this.name=name;
}
public Object clone()throws CloneNotSupportedException
{
return super.clone();
}
public static void main(String args[]){
try
{
Student18 s1=new Student18(101,"amit");
Student18 s2=(Student18)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}
catch(CloneNotSupportedException c)
{
}
}
}
Output:
101 amit
101 amit

Page 52 of 52

You might also like