0% found this document useful (0 votes)
11 views24 pages

Java Module 2

Uploaded by

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

Java Module 2

Uploaded by

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

MODULE 2

Method Overloading
What is Method Overloading?
Method Overloading is a feature in Java where a class can have multiple methods with the same
name but different parameter lists (type, number, or order).
It is a form of compile-time polymorphism.
Why Use Method Overloading?
 To perform similar operations in different ways.
 Improves code readability and reusability.
Rules for Overloading
 Methods must have different parameter lists.
 Can have different return types, but return type alone is not enough to overload a method.
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(2, 3)); // 5
System.out.println(c.add(2.5, 3.5)); // 6.0
System.out.println(c.add(1, 2, 3)); // 6
}
}
Using Objects as Parameters
Why Use Objects as Parameters?
Passing an object as a parameter allows one class to use the data or behavior of another class.
This supports:
 Code modularity
 Encapsulation
 Code reuse
Example:
class Student {
String name;
int age;
Student(String n, int a) {
name = n;
age = a;
}
void display() {
System.out.println(name + " is " + age + " years old.");
}
}
class DisplayDetails {
void printStudent(Student s) {
s.display(); // calling method of Student class
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Alice", 20);
DisplayDetails d = new DisplayDetails();
d.printStudent(s1); // Passing object as parameter
}
}
Output:
Alice is 20 years old.
Returning Objects from Methods
What is it?
In Java, a method can return an object instead of a primitive type. This allows chaining of object
operations and building modular code.
Example:
java
CopyEdit
class Rectangle {
int length, width;
Rectangle(int l, int w) {
length = l;
width = w;
}
Rectangle larger(Rectangle r2) {
int area1 = this.length * this.width;
int area2 = r2.length * r2.width;
return (area1 > area2) ? this : r2; // returning the larger rectangle
}
void display() {
System.out.println("Length: " + length + ", Width: " + width);
}
}
public class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(4, 5);
Rectangle r2 = new Rectangle(3, 6);

Rectangle big = r1.larger(r2); // method returns an object


System.out.print("Larger Rectangle: ");
big.display();
}
}
Output:
Larger Rectangle: Length: 4, Width: 5
Summary

Concept Description

Objects as Enables reuse of data and methods of an object in another


Parameters class
Returning Objects Allows method to send back an object for further operations

Static Members in Java


What is static in Java?
The static keyword in Java is used for memory management. It makes a member (variable or
method) belong to the class rather than an instance of the class.
Types of Static Members:
1. static variables (class variables)
2. static methods
3. static blocks
4. static nested classes
1.1 Static Variable
 Shared among all objects of a class.
 Stored in method area (not heap).
 Initialized only once at class loading time.
Example:
class Student {
int rollNo;
static String college = "ABC College"; // static variable

Student(int r) {
rollNo = r;
}
void display() {
System.out.println(rollNo + " - " + college);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(101);
Student s2 = new Student(102);
s1.display();
s2.display();
}
}
Output:
101 - ABC College
102 - ABC College
1.2 Static Method
 Can be called without creating an object.
 Can only access static data directly.
 Cannot use this or super.
Example:
class MathUtils {
static int square(int x) {
return x * x;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(MathUtils.square(5)); // no object needed
}
}

1.3 Static Block


 Used to initialize static variables.
 Runs once when the class is loaded.
Example:
class Demo {
static int x;
static {
x = 10;
System.out.println("Static block initialized.");
}
static void show() {
System.out.println("x = " + x);
}
}
public class Main {
public static void main(String[] args) {
Demo.show();
}
}
Final Variables in Java
What is final in Java?
The final keyword is used to declare constants. Once assigned, a final variable's value cannot be
changed.
Types of Final Usage:
1. Final variable
2. Final method
3. Final class

2.1 Final Variable


 Value is assigned only once.
 If not initialized during declaration, it must be initialized in a constructor or static block.
Example:
class Circle {
final double PI = 3.14159; // constant
double area(double r) {
return PI * r * r;
}
}

2.2 Final Method


 Cannot be overridden by subclasses.
class A {
final void show() {
System.out.println("This is a final method.");
}
}
class B extends A {
// void show() {} Compilation error
}

2.3 Final Class


 Cannot be extended (no subclassing).
final class Animal {
void sound() {
System.out.println("Animal sound");
}
}

// class Dog extends Animal {} Error: Cannot inherit from final class
What is an Inner Class?
An Inner Class is a class defined inside another class. Java allows nesting classes to logically group
classes that are only used in one place, increasing encapsulation and readability.
Why Use Inner Classes?
 Logical grouping of classes
 Better encapsulation
 Can access members (even private ones) of the outer class
 Useful in event handling, GUI applications, etc.
Types of Inner Classes in Java:

Type Description
1. Member Inner Class Regular class defined within another class.
2. Static Nested Class Static class defined inside another class. Doesn’t need outer class object.
3. Local Inner Class Defined inside a method or block.
4. Anonymous Inner A class without a name, used for one-time use (like in GUI event
Class handling).

1. Member Inner Class (Non-static)


Example:
class Outer {
int outerVar = 100;
class Inner {
void show() {
System.out.println("Outer variable: " + outerVar);
}
}
}
public class Main {
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner(); // Create inner object
inner.show();
}
}
2. Static Nested Class
 Can only access static members of the outer class.
 Does not need an instance of the outer class to be created.
Example:
class Outer {
static int data = 30;
static class StaticInner {
void display() {
System.out.println("Data: " + data);
}
}
}
public class Main {
public static void main(String[] args) {
Outer.StaticInner obj = new Outer.StaticInner();
obj.display();
}
}
3. Local Inner Class
 Defined inside a method.
 Only accessible within that method.
 Can access final or effectively final variables of the method.
Example:
class Outer {
void outerMethod() {
int num = 50; // effectively final

class LocalInner {
void display() {
System.out.println("Number: " + num);
}
}
LocalInner inner = new LocalInner();
inner.display();
}
}
public class Main {
public static void main(String[] args) {
Outer outer = new Outer();
outer.outerMethod();
}
}
4. Anonymous Inner Class
 A class with no name.
 Used to implement an interface or extend a class on the fly.
 Commonly used in GUI or event handling.
Example:
abstract class Greeting {
abstract void sayHello();
}
public class Main {
public static void main(String[] args) {
Greeting g = new Greeting() {
void sayHello() {
System.out.println("Hello from anonymous class!");
}
};
g.sayHello();
}
}
Summary Table

Access to Outer Static


Type of Inner Class Common Use Case
Class ?
Accessing outer class instance
Member Inner Class Yes No
members
Static Nested Class Only static Yes Utility grouping
Local Inner Class Yes (final vars only) No Temporary use inside method
Anonymous Inner
Yes No Event handling / one-time use
Class

What is a Superclass?
A superclass (also called base class or parent class) is a class that is inherited by another class. It
defines common attributes and methods that can be shared by other classes.
Key points:
 A superclass can be reused by multiple subclasses.
 It may be abstract (not directly instantiated).
 It provides common functionality to be extended or overridden.
What is a Subclass?
A subclass (also called derived class or child class) is a class that inherits from another class using
the extends keyword. It can:
 Use the methods and variables of the superclass.
 Add new methods or fields.
 Override superclass methods.
Syntax of Inheritance in Java:
class Superclass {
// fields and methods
}
class Subclass extends Superclass {
// additional fields and methods
}
Example:
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited from Animal (superclass)
myDog.bark(); // Defined in Dog (subclass)
}
}
Output:
This animal eats food.
The dog barks.
Key Differences

Feature Superclass Subclass


Class that extends another
Definition Class being extended
Inheritance
Role Provider of features Receiver of features
Reusability Offers reusable code Reuses and adds functionality
Access Cannot access subclass directly Can access superclass members

Accessing Superclass Members


A subclass can access public and protected members of the superclass. It cannot access private
members directly.
What is Inheritance in Java?
Inheritance is the process by which one class (child) acquires the properties and behaviors (fields
and methods) of another class (parent).
It promotes code reusability and is a key feature of object-oriented programming.
Syntax:
class Parent {
// parent members
}
class Child extends Parent {
// child members
}
Types of Inheritance in Java:

Type Description
1. Single Inheritance One class inherits from another.
A class inherits from a class which is already inherited from another
2. Multilevel Inheritance
class.
3. Hierarchical
Multiple classes inherit from a single parent class.
Inheritance
4. Hybrid Inheritance Combination of multiple types (achievable via interfaces in Java).
Note: Java does not support multiple inheritance with classes to avoid ambiguity (Diamond
Problem). But it is allowed through interfaces.
1. Single Inheritance
A child class inherits directly from a parent class.
Example:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // inherited
d.bark(); // own method
}
}
2. Multilevel Inheritance
A class inherits from a class which itself inherits from another class.
Example:
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
class Puppy extends Dog {
void weep() {
System.out.println("Weeping...");
}
}

public class Main {


public static void main(String[] args) {
Puppy p = new Puppy();
p.eat();
p.bark();
p.weep();
}
}
3. Hierarchical Inheritance
Multiple classes inherit from a single parent class.
Example:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
Cat c = new Cat();
d.sound();
c.sound();
}
}
4. Hybrid Inheritance (via Interfaces)
Java does not allow multiple inheritance with classes but allows it through interfaces, achieving
hybrid inheritance.
Example:
interface A {
void methodA();
}
interface B {
void methodB();
}
class C implements A, B {
public void methodA() {
System.out.println("Method A");
}
public void methodB() {
System.out.println("Method B");
}
}
public class Main {
public static void main(String[] args) {
C obj = new C();
obj.methodA();
obj.methodB();
}
}
Why Java Does Not Support Multiple Inheritance with Classes?
To avoid ambiguity caused by the Diamond Problem.
Example of Diamond Problem (Not allowed in Java):
A
/\
B C
\/
D
If both B and C inherit a method from A, and D inherits from both B and C, which method
should D use? To prevent this confusion, Java restricts multiple inheritance of classes, but allows it
via interfaces.
Summary Table:

Type Supports in Java Example Components


Single Inheritance
Yes One child, one parent
Grandparent → Parent →
Multilevel Inheritance Yes
Child
Hierarchical Inheritance Yes One parent, many children
(with classes)
Multiple Inheritance Interfaces only
(with interfaces)
Hybrid Inheritance via interfaces Mix of inheritance types

super Keyword in Java


The super keyword is used in a subclass to refer to members (variables or methods) of its
immediate superclass.
Uses of super:
1. Access superclass constructor
2. Access superclass methods
3. Access superclass variables
1. Using super() to Call Superclass Constructor
By default, when a subclass constructor is called, it implicitly calls the no-argument constructor of
the superclass using super().

class Animal {
Animal() {
System.out.println("Animal constructor called");
}
}
class Dog extends Animal {
Dog() {
super(); // optional here, Java adds it automatically
System.out.println("Dog constructor called");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
}
}
Output:
Animal constructor called
Dog constructor called

2. Using super to Access Superclass Method


class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
super.sound(); // calling superclass method
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
}
}

3. Using super to Access Superclass Variable


class Animal {
String name = "Animal";
}
class Dog extends Animal {
String name = "Dog";
void printNames() {
System.out.println(name); // Dog
System.out.println(super.name); // Animal
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.printNames();
}
}

Order of Constructor Calls in Inheritance


In Java, when a subclass object is created:
1. Superclass constructor is called first
2. Then the subclass constructor is called
This ensures that the parent part of the object is initialized before the child part.
Example:
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();
}
}
Output:
Constructor of A
Constructor of B
Constructor of C
Even though we only created an object of class C, constructors of B and A are called first, in that
order.

Summary

Concept Description
Calls the immediate superclass constructor. Must be the first statement in
super()
subclass constructor.
super.method() Calls a method from the superclass.
super.variable Accesses a variable from the superclass (if hidden by subclass variable).
Constructor Call
Parent constructor → Child constructor
Order

What is Method Overriding in Java?


Method overriding in Java occurs when a subclass provides a specific implementation of a
method that is already defined in its superclass.
The overridden method in the subclass should have:
 Same method name
 Same return type (or subtype - called covariant return type)
 Same parameter list
Purpose of Overriding
To implement runtime polymorphism, where the method that gets called depends on the object's
runtime type, not the reference type.
Example of Method Overriding
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
// Overriding the sound() method
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
a.sound(); // Calls Dog's overridden method
}
}
Output:
Dog barks
Key Points about Method Overriding

Rule / Feature Description


Same Signature Name and parameters must be identical
Can’t be more restrictive than the superclass
Access Modifier
method
Return Type Must be the same or a subtype (covariant)
@Override Annotation Optional but recommended – helps catch errors
Static/Private/Final
Cannot be overridden
Methods
Constructors Cannot be overridden
Access Modifier Example
class Parent {
protected void show() {
System.out.println("Parent class");
}
}
class Child extends Parent {
// Must be same or more visible (protected or public)
@Override
public void show() {
System.out.println("Child class");
}
}
Invalid Overriding Example (Compile-time Error)
class Parent {
private void show() {
System.out.println("Parent");
}
}
class Child extends Parent {
@Override
void show() { // Cannot override private method
System.out.println("Child");
}
}
Explanation: show() in Parent is private – not visible to Child.
Method Overloading vs Method Overriding

Method
Feature Method Overriding
Overloading
Between superclass and
Occurs in Same class
subclass
Parameters Must differ Must be the same
Return Type Can differ Must be same or subtype
Access Modifier Any Cannot be more restrictive
Polymorphism
Compile-time Runtime
Type
Real-world Analogy
Think of a base class Printer that prints documents. A ColorPrinter (subclass) can override the
method to print in color, while BlackAndWhitePrinter prints in black-and-white – same
method, different behavior.
Dynamic Method Dispatch in Java
Dynamic Method Dispatch is a mechanism in Java that determines which version of an
overridden method to call at runtime, not compile time. It is the core of runtime
polymorphism in Java.

Definition:
Dynamic Method Dispatch refers to the process by which a call to an overridden method is resolved
at runtime rather than at compile time.
This happens when a superclass reference is used to refer to a subclass object.
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal a; // superclass reference
a = new Dog(); // subclass object
a.sound(); // calls Dog's sound()
a = new Cat(); // new subclass object
a.sound(); // calls Cat's sound()
}
}

Output:
Dog barks
Cat meows
Key Concepts:

Concept Description
Polymorphism Same interface, different behaviors
Method Overriding Required for dynamic dispatch
Superclass reference Refers to subclass objects
Late Binding (Runtime The method to execute is selected during program
Binding) execution
⚠ Important Notes:

 Only non-static, non-final, and non-private methods are dynamically dispatched.


 Constructors are not involved in dynamic dispatch.
 Static methods are resolved at compile time (called early binding).
Real-life Analogy:
Think of a remote control (reference variable of superclass type). You can use the same remote
to control a TV, AC, or Fan (objects of different subclasses). What actually happens depends on
the object you connect the remote to.
Summary:
 Dynamic Method Dispatch = deciding at runtime which overridden method to call.
 Enables runtime polymorphism.
 Improves flexibility and extensibility in object-oriented design.

You might also like