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

Module II Java

This document covers various concepts in Java, including method overloading, recursive functions, using objects as parameters, returning objects, inheritance, and method overriding. It explains the types of inheritance, the use of the super keyword, and the final keyword in the context of inheritance. Additionally, it discusses static members and inner classes, providing examples for each concept.

Uploaded by

keerthana4003
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 views21 pages

Module II Java

This document covers various concepts in Java, including method overloading, recursive functions, using objects as parameters, returning objects, inheritance, and method overriding. It explains the types of inheritance, the use of the super keyword, and the final keyword in the context of inheritance. Additionally, it discusses static members and inner classes, providing examples for each concept.

Uploaded by

keerthana4003
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

MODULE II

Java Method Overloading


● In Java, two or more methods can have the same name if they differ in parameters (different
number of parameters, different types of parameters, or both).
● These methods are called overloaded methods and this feature is called method overloading.
● It is a form of compile-time polymorphism.

For example:

void display() {

...

void display(int a) {

...

Here, the func() method is overloaded. These methods have the same name but accept
different arguments.

The return type of these methods is not the same. Overloaded methods may or may not have
different return types, but they must differ in parameters they accept.

Overloading by changing the number of arguments

class MethodOverloading {
public void display(int a) {
[Link]("Arguments: " + a);
}
public void display(int a, int b) {
[Link]("Arguments: " + a + " and " + b);
}

public static void main(String[] args) {


MethodOverloading obj = new MethodOverloading();

[Link](1);
[Link](1, 4);

1
}
}

By changing the datatype of parameters


class MethodOverloading {
public void display(int a) {
[Link]("Got Integer data.");
}
public void display(String a) {
[Link]("Got String object.");
}

public static void main(String[] args) {


MethodOverloading obj = new MethodOverloading();
[Link](1); // Calls int version
[Link]("Hello"); // Calls String version
}
}

Recursive Functions in Java


A recursive function is a method that calls itself to solve a problem.

🔹 Key Concepts
1. Base Case – condition to stop recursion
2. Recursive Case – where the method calls itself

🔁 Recursion breaks the problem into smaller subproblems until the base case is
reached.

Example : Factorial of a Number


Problem: Calculate n! = n × (n-1) × (n-2) × ... × 1

public class Factorial {


static int factorial(int n) {
if (n == 0) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive call
}

2
public static void main(String[] args) {
int result = factorial(5);
[Link]("Factorial of 5 is " + result);
}
}
Output:
Factorial of 5 is 120

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.

Example:
class Student {

String name;
int age;

Student(String n, int a) {
name = n;
age = a;
}

void display() {
[Link](name + " is " + age + " years old.");
}
}

public class Main {


static void printStudent(Student s) {
[Link](); // using object as parameter
}

public static void main(String[] args) {


Student s1 = new Student("Alice", 20);
printStudent(s1);
}
}

3
Output:
Alice is 20 years old.

Returning Objects in Java


In Java, methods can return objects just like they return int, String, or other data types.
Sometimes, you want a method to give back a complete object with its data and behavior, not
just a single value.

Example

// Define a class
class Student {
String name;
int age;

// Method to set values


void setDetails(String n, int a) {
name = n;
age = a;
}
// Method to display details
void display() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
// Method that returns a Student object
Student getStudent() {
Student s = new Student(); // create new object
[Link]("Anu", 20); // set values
return s; // return object
}
}

// Main class
public class Main {
public static void main(String[] args) {
Student obj = new Student(); // create object
Student result = [Link](); // get returned object
[Link](); // call method on returned object
}
}

4
OUTPUT:

Name: Anu
Age: 20

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

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.

Subclass
A subclass (also called derived class or child class) is a class that inherits from another
class using the extends keyword.
🔑 Syntax:

class Parent {
// parent members
}
class Child extends Parent {
// child members
}
📘 Example:
// Superclass
class Animal {
void eat() {
[Link]("This animal eats food.");
}
}
// Subclass
class Dog extends Animal {
void bark() {
[Link]("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {

5
Dog myDog = new Dog();
[Link](); // Inherited from Animal (superclass)
[Link](); // Defined in Dog (subclass)
}
}
Output:
This animal eats food.
The dog barks.

Types of Inheritance in Java:


Type Description
1. Single Inheritance One class inherits from another.
2. Multilevel Inheritance A class inherits from a class which is already
inherited from another class.
3. Hierarchical Inheritance Multiple classes inherit from a single parent
class.
4. Hybrid Inheritance Combination of multiple types

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() {
[Link]("Animal makes sound");
}
}
class Dog extends Animal {
void bark() {
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // inherited

6
[Link](); // own method
}
}

🔹 2. Multilevel Inheritance
A class inherits from a class which itself inherits from another class.

📌 Example:
class Animal {
void eat() {
[Link]("Eating...");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
}
class Puppy extends Dog {
void weep() {
[Link]("Weeping...");
}
}
public class Main {
public static void main(String[] args) {
Puppy p = new Puppy();
[Link]();
[Link]();
[Link]();
}
}

🔹 3. Hierarchical Inheritance
Multiple classes inherit from a single parent class.

📌 Example:
class Animal {
void sound() {
[Link]("Animal sound");
}
7
}
class Dog extends Animal {
void bark() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
void meow() {
[Link]("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
Cat c = new Cat();
[Link]();
[Link]();
}
}

🔹 4. Hybrid Inheritance (combination of class and multiple 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() {
[Link]("Method A");
}

public void methodB() {


[Link]("Method B");
}
}

8
public class Main {
public static void main(String[] args) {
C obj = new C();
[Link]();
[Link]();
}
}

🚫 Why Java Does Not Support Multiple Inheritance with Classes

Multiple Inheritance-A class trying to inherit from more than one class at the same time.

Example (not allowed in Java):

class A { }
class B { }

class C extends A, B { } // Not allowed in Java

👉 Reason: Ambiguity

If both parent classes have a method with the same name, Java won’t know which one to
use.

class A {
void show() {
[Link]("Show from A");
}
}

class B {
void show() {
[Link]("Show from B");
}
}
// Java does NOT allow this
class C extends A, B {
public static void main(String[] args) {
C obj = new C();
[Link](); // Should it call A's or B's show()?
}
}

9
● Both A and B have a method show().

● When you call [Link](), Java doesn’t know:

○ A's show() or

○ B's show()?

That’s called ambiguity, and Java avoids this by not allowing multiple inheritance with
classes.
Java allows multiple inheritance using interfaces, not classes.

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() {
[Link]("Animal constructor called");
}
}

class Dog extends Animal {


Dog() {
super(); // optional here, Java adds it automatically
[Link]("Dog constructor called");
}
}

public class Main {


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

10
Output:
Animal constructor called
Dog constructor called

2. Using super to Access Superclass Method

class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
[Link](); // calling superclass method
[Link]("Dog barks");
}
}

public class Main {


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

3. Using super to Access Superclass Variable

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

11
}

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() {
[Link]("Constructor of A");
}
}

class B extends A {
B() {
[Link]("Constructor of B");
}
}

class C extends B {
C() {
[Link]("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

12
Even though we only created an object of class C, constructors of B and A are called first, in that order

Method Overriding
Method Overriding means redefining a method in the child class that already exists in the
parent class with the same name and parameters.

This allows the child class to provide a specific implementation of a method that is already
defined in its parent class.

Example Program:
// Parent class
class Vehicle {
void run() {
[Link]("Vehicle is running");
}
}

// Child class
class Bike2 extends Vehicle {
void run() {
[Link]("Bike is running safely");
}
}

public class Test {


public static void main(String[] args) {

Bike2 obj = new Bike2(); // Creating object of child class


[Link](); // Calls the overridden method in Bike2
}
}
● Overriding only works in inheritance (when a class extends another).
● Method name, return type, and parameters must match exactly.
● It allows for runtime polymorphism

Dynamic Method Dispatch in Java


Dynamic Method Dispatch (also called runtime polymorphism) is the process where a call to
an overridden method is resolved at runtime rather than compile time.

13
● A parent class reference is used to refer to a child class object
● And the overridden method is called

Example:
class Vehicle {
void run() {
[Link]("Vehicle is running");
}
}
class Bike extends Vehicle {
void run() {
[Link]("Bike is running safely");
}
}
public class Test {
public static void main(String[] args) {
Vehicle obj = new Bike(); // Upcasting
[Link](); // Runtime: calls Bike's run() method
}
}
🔹 Output:
Bike is running safely
● At compile-time, Java only knows that obj is a Vehicle.
● At runtime, it sees that the actual object is a Bike, so it calls the Bike version of run().

14
final keyword with inheritance in java
● we cannot override a final method in Java.
● Final methods can be inherited in java

15
class Bike{

final void run()


{
[Link]("running");
}
}
public class Honda extends Bike{
void run1() {
[Link]("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
[Link]();
honda .run1();
}
}
output

running
running safely with 100kmph

16
Static Members in Java
In Java, static members belong to the class, not to instances (objects) of the class. This means:

● They are shared among all objects of the class.

● You can access them without creating an object.

Types of Static Members:

1. Static Variables (Class Variables)

2. Static Methods

3. Static Blocks

4. Static Classes (Nested only)

Static Variables

● Declared using the static keyword inside a class.


● Only one copy is created, shared by all objects.

class Student {
int id;
String name;
static String college = "ABC College"; // static variable
Student(int i, String n) {
id = i;
name = n;
}
void display() {
[Link](id + " " + name + " " + college);
}}
public class Test {
public static void main(String[] args) {
Student s1 = new Student(1, "Alice");
Student s2 = new Student(2, "Bob");

[Link]();
[Link]();
}
}

17
No matter how many Student objects you create, college will remain the same.

Output:

1 Alice ABC College


2 Bob ABC College
If you change the static variable, the change will reflect for all objects.

Static Methods

You can create a static method by using the keyword static

To access static methods there is no need to instantiate the class(create an object).

public class MyClass {


public static void sample(){
[Link]("Hello");
}
public static void main(String args[]){
sample();
}}
Output
Hello

Static Block
● Used to initialize static variables.
● Runs once when the class is loaded.

🔹 Example:
class Demo {
static int x;

static {
x = 10;
[Link]("Static block initialized.");
}
static void show() {
[Link]("x = " + x);
}
}
public class Main {

18
public static void main(String[] args) {
[Link]();
}
}

Output:
Static block initialized.
x = 10

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.

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.

🔷 1. Member Inner Class (Non-static)


📌 Example:
class Outer {
int outerVar = 100;

class Inner {
void show() {
[Link]("Outer variable: " + outerVar);
}

19
}
}

public class Main {


public static void main(String[] args) {
Outer outer = new Outer();
[Link] inner = [Link] Inner(); // Create inner object
[Link]();
}
}

🔷 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() {
[Link]("Data: " + data);
}
}
}

public class Main {


public static void main(String[] args) {
[Link] obj = new [Link]();
[Link]();
}
}

🔷 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() {

20
int num = 50; // effectively final

class LocalInner {
void display() {
[Link]("Number: " + num);
}
}

LocalInner inner = new LocalInner();


[Link]();
}
}

public class Main {


public static void main(String[] args) {
Outer outer = new Outer();
[Link]();
}
}

21

You might also like