0% found this document useful (0 votes)
50 views22 pages

Unit Ii-Apj

The document covers key concepts in Java programming, focusing on inheritance, method overloading, and the use of objects as parameters. It explains method overloading techniques, the significance of passing objects and returning objects from methods, as well as the use of static fields and methods. Additionally, it discusses nested and inner classes, and various types of inheritance in Java, including single, multilevel, hierarchical, and multiple inheritance through interfaces.

Uploaded by

jesudosss
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)
50 views22 pages

Unit Ii-Apj

The document covers key concepts in Java programming, focusing on inheritance, method overloading, and the use of objects as parameters. It explains method overloading techniques, the significance of passing objects and returning objects from methods, as well as the use of static fields and methods. Additionally, it discusses nested and inner classes, and various types of inheritance in Java, including single, multilevel, hierarchical, and multiple inheritance through interfaces.

Uploaded by

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

UNIT II

INHERITANCE, PACKAGES AND INTERFACES: Overloading Methods – Objects as Parameters,


Returning Objects, Static, Nested and Inner Classes- Inheritance: Basics, Types of Inheritance, Super
keyword, Method Overriding, Dynamic Method Dispatch, Abstract Classes, final with Inheritance -
Packages and Interfaces- Packages, Packages and Member Access, Importing Packages, Interfaces.

OVERLOADING METHODS
 To define two or more methods within the same class that share the same name, as long as their
parameter declarations are different. When this is the case, the methods are said to be
overloaded, and the process is referred to as method overloading.
 Method overloading is one of the ways that Java supports polymorphism.
 When an overloaded method is invoked, Java uses the type and/or number of arguments as its
guide to determine which version of the overloaded method to actually call.
 Thus, overloaded methods must differ in the type and/or number of their parameters.
 While overloaded methods may have different return types, the return type alone is insufficient to
distinguish two versions of a method.
 When Java encounters a call to an overloaded method, it simply executes the version of the method
whose parameters match the arguments used in the call.

Here is a simple example that illustrates method overloading:

// Demonstrate method overloading.


class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// Overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
This program generates the following output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625

 test( ) is overloaded four times.


 The first version takes no parameters,
 the second takes one integer parameter,
 the third takes two integer parameters,
 and the fourth takes one double parameter.
 The fact that the fourth version of test( ) also returns a value is of no consequence
relative to overloading, since return types do not play a role in overload resolution.
 When an overloaded method is called, Java looks for a match between the arguments
used to call the method and the method’s parameters.
Different Ways of Method Overloading in Java
 Changing the Number of Parameters.
 Changing Data Types of the Arguments.
 Changing the Order of the Parameters of Methods
1. Changing the Number of Parameters
A method can be overloaded by varying the number of parameters.
Example:
class OverloadExample {
void display(int a) {
System.out.println("One parameter: " + a);
}
void display(int a, int b) {
System.out.println("Two parameters: " + a + ", " + b);
}
public static void main(String[] args) {
OverloadExample obj = new OverloadExample();
obj.display(10);
obj.display(10, 20);
}
}
Output:
One parameter: 10
Two parameters: 10, 20
2. Changing Data Types of the Arguments
Overloading can be done by changing the data type of parameters.

Example:
class OverloadExample {
void show(int a) {
System.out.println("Integer: " + a);
}

void show(double a) {
System.out.println("Double: " + a);
}

public static void main(String[] args) {


OverloadExample obj = new OverloadExample();
obj.show(10); // Calls the int version
obj.show(10.5); // Calls the double version
}
}
Output:

Integer: 10
Double: 10.5
3. Changing the Order of Parameters
Overloading can also be done by changing the order of different types of parameters.

Example:
class OverloadExample {
void print(String str, int num) {
System.out.println("String: " + str + ", Integer: " + num);
}
void print(int num, String str) {
System.out.println("Integer: " + num + ", String: " + str);
}

public static void main(String[] args) {


OverloadExample obj = new OverloadExample();
obj.print("Java", 100);
obj.print(200, "Overloading");
}
}
Output:

String: Java, Integer: 100


Integer: 200, String: Overloading

OBJECTS AS PARAMETER
 In Java, objects can be passed as parameters to methods, just like primitive data types.
 When an object is passed as a parameter, it is actually the reference to the object that is passed, not
the actual object itself.
 This means that changes made to the object's fields inside the method will affect the original object
outside the method
Example: Passing an Object as a Parameter
This Java program demonstrates passing an object as a parameter to a method and
modifying its properties.
1. Class Definition (Person)
class Person {
String name;
Person(String name) {
this.name = name;
}
void changeName(String newName) {
this.name = newName;
}
}
 The Person class has a field name (a String).
 A constructor initializes the name when an object is created.
 A method changeName(String newName) allows changing the name of the object.
2. Method to Modify Object (modifyPerson)
static void modifyPerson(Person p) {
p.name = "Updated Name"; // Modifies the original object
}
 This method accepts a Person object (p) as a parameter.
 It directly modifies the name field of the Person object.

3. main Method Execution


public static void main(String[] args) {
Person person1 = new Person("John");
System.out.println("Before modification: " + person1.name);
 Creates a Person object person1 with name = "John".
 Prints the initial name:

Output: Before modification: John


modifyPerson(person1); // Passing object as a parameter
System.out.println("After modification: " + person1.name);

 Calls modifyPerson(person1), passing person1 by reference.


 Inside modifyPerson, p.name is changed to "Updated Name", affecting person1.
 The new name is printed:

Output: After modification: Updated Name

1. Objects in Java are passed by reference.


2. Changing object properties affects the original instance.
3. If we reassign the parameter inside the method, it does not affect the original
reference.

RETURNING OBJECTS
A method can return an object instead of primitive data types like int, char, boolean, etc.
This allows us to return complex data structures, making programs more modular and efficient.
Why Return an Object
Returning objects is useful in many situations, such as:
1. Encapsulation of Data – Objects store multiple related data fields, making them ideal
return types.
2. Reusability – Methods can return objects that can be used elsewhere in the program.
3. Method Chaining – Returning this allows method calls to be chained together.
4. Factory Methods – Methods that create and return objects dynamically.

Ways to Return an Object in Java


1. Returning the Current Object (this)
 The this keyword refers to the current instance of the class.
 Useful for returning the calling object.
Example:
class Example {
int num;
Example(int num) {
this.num = num;
}
// Returning current object
Example getInstance() {
return this;
}
void display() {
System.out.println("Number: " + num);
}
public static void main(String[] args) {
Example obj = new Example(10);
obj.getInstance().display(); // Returning and calling a method on the returned object
}
}
2. Returning a New Object
 A method can return a completely new object.
 Useful when modifying or creating fresh instances.
Example:
class Calculator {
int value;
Calculator(int value) {
this.value = value;
}
// Returning a new object with modified value
Calculator add(int num) {
return new Calculator(this.value + num);
}
void display() {
System.out.println("Value: " + value);
}
public static void main(String[] args) {
Calculator calc1 = new Calculator(10);
Calculator calc2 = calc1.add(20); // Returning a new object
calc1.display();
calc2.display();
}
}
Output:
Value: 10
Value: 30
Here, calc1.add(20) returns a new Calculator object instead of modifying calc1.

3. Returning an Object Based on Conditions


 Useful in decision-making scenarios where different objects are needed.
Example:
class Animal {
String type;
Animal(String type) {
this.type = type;
}
// Returning an object based on a condition
static Animal getAnimal(boolean isWild) {
if (isWild)
return new Animal("Tiger");
else
return new Animal("Dog");
}
void display() {
System.out.println("Animal Type: " + type);
}
public static void main(String[] args) {
Animal wildAnimal = Animal.getAnimal(true);
Animal petAnimal = Animal.getAnimal(false);
wildAnimal.display();
petAnimal.display();
}
}
Output:
Animal Type: Tiger
Animal Type: Dog
Here, the method getAnimal returns different objects based on the boolean condition.
Returning objects in Java enhances flexibility and improves code reusability. It allows creating
dynamic methods that generate, modify, and return objects based on logic. This is widely used in
frameworks, libraries, and real-world applications.

STATIC FIELDS AND METHODS


 The static keyword in java is used for memory management mainly.
 We can apply java static keyword with variables, methods, blocks and nested class.
 The static keyword belongs to the class than instance of the class.
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class
Java static variable
If declare any variable as static, it is known static variable.
o The static variable can be used to refer the common property of all objects (that is not unique for
each object) e.g. company name of employees,college name of students etc.
o The static variable gets memory only once in class area at the time of classloading.
Advantage of static variable
It makes program memory efficient (i.e it saves memory).

Example of static variable


//Program of static variable
class Student8
{
int rollno;
String name;
static String college ="RGCET";
Student8(int r,String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
}}
Java static method
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o static method can access static data member and can change the value of it
Java static block
o Is used to initialize the static data member.
o It is executed before main method at the time of class loading.

JAVA NESTED AND INNER CLASSES


 Java inner class or nested class is a class which is declared inside the class or interface.
 We use inner classes to logically group classes and interfaces in one place so that it can be
more readable and maintainable.
Syntax of Inner class
1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. } }

Advantage of java inner classes


There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.
Difference between nested class and inner class in Java
Inner class is a part of nested class. Non-static nested classes are known as inner classes.
Types of Nested classes
There are two types of nested classes non-static and static nested classes.The non-static nested
classes are also known as inner classes.
o Non-static nested class (inner class)
1. Member inner class
2. Anonymous inner class
3. Local inner class
o Static nested class

INHERITANCE IN JAVA
 Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object. Inheritance represents the IS-A relationship, also known as
parentchild relationship.
Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
The extends keyword is used for class inheritance to indicate that a class is inheriting from a parent
(superclass). The basic syntax is:
Syntax:
class ParentClass {
// Parent class members (fields, methods, constructors)
}
class ChildClass extends ParentClass {
// Child class members (fields, methods, constructors)
}

TYPES OF INHERITANCE

Single Inheritance
 In this type of inheritance, a subclass (child class) inherits from a single superclass (parent
class).
 It enables code reuse from a single base class.
 syntax
class Parent {
// Parent class members
}

class Child extends Parent {


// Child class members
}
Multilevel Inheritance
 A class inherits from another derived class, forming a chain of inheritance.
 Syntax
class GrandParent {
// Grandparent class members
}
class Parent extends GrandParent {
// Parent class members
}
class Child extends Parent {
// Child class members
}
Hierarchical Inheritance
 Multiple child classes inherit from a single parent class.
 Syntax
class Parent {
// Parent class members
}

class Child1 extends Parent {


// Child1 members
}

class Child2 extends Parent {


// Child2 members
}
Multiple Inheritance (via Interfaces)
 Java does not support multiple inheritance with classes to avoid ambiguity (Diamond
Problem).
 However, it supports multiple inheritance using interfaces.
 Syntax
interface Interface1 {
// Methods
}

interface Interface2 {
// Methods
}

class ClassName implements Interface1, Interface2 {


// Implement methods from Interface1 and Interface2
}
Hybrid Inheritance (Combination of Types)
 Java does not support hybrid inheritance directly using classes because of ambiguity
issues.
 However, it can be achieved using interfaces.
 Syntax
interface Interface1 {
// Methods
}

interface Interface2 {
// Methods
}

class Parent {
// Parent class members
}

class Child extends Parent implements Interface1, Interface2 {


// Implement methods from interfaces
}
Type of Inheritance Syntax
Single Inheritance class Child extends Parent {}
Multilevel Inheritance class C extends B extends A {}
Hierarchical Inheritance class B extends A {}, class C extends A {}
Multiple Inheritance (via Interfaces) class C implements A, B {}
Hybrid Inheritance (via Interfaces) class C extends A implements B, D {}

Single Inheritance Example


File: TestInheritance.java
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...
Multilevel Inheritance Example
File: TestInheritance2.java
class Animal{
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.e at();

}}
Output:
weeping... barking... eating...
Hierarchical Inheritance Example
File: TestInheritance3.java
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{
public static void main(String args[]){ Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing... eating...

super keyword in java


 The super keyword in java is a reference variable which is used to refer immediate parent class
object.
 Whenever you create the instance of subclass, an instance of parent class is created implicitly which
is referred by super reference variable.
Usage of java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor.

super is used to refer immediate parent class instance variable.


class Animal{
String color="white";
}
class Dog extends Animal{ String color="black";
void printColor(){ System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){ Dog d=new Dog();
d.printColor();
}}
Output:
black white

Final Keyword in Java

 The final keyword in Java is used to apply restrictions on variables, methods, and classes.
It prevents modification of values, method overriding, and inheritance
1. Final Variable (Constant)
 A final variable can be assigned only once. Once assigned, its value cannot be changed.

class Example {
final int MAX_VALUE = 100;

2. Final Method (Prevents Overriding)


 A final method cannot be overridden by subclasses.

class Parent {
final void show() {
System.out.println("Final method in Parent class");
}
}

3. Final Class (Prevents Inheritance)


 A final class cannot be extended (inherited).

final class FinalClass {


void display() {
System.out.println("Final class method");
}
}
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java.

Usage of Java Method Overriding


o Method overriding is used to provide specific implementation of a method that is already provided
by its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

Example program:

// Parent class
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}

// Child class overriding the makeSound() method


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

public class Main {


public static void main(String[] args) {
Animal myAnimal = new Animal(); // Parent class object
myAnimal.makeSound(); // Calls Animal's makeSound()

Dog myDog = new Dog(); // Child class object


myDog.makeSound(); // Calls Dog's overridden makeSound()
}
}

Output:
Animal makes a sound
Dog barks
Explanation:
 The makeSound() method is defined in the Animal class.
 The Dog class overrides makeSound() to provide its own implementation.
 When we call makeSound() on an Animal object, it calls the Animal class method.
 When we call makeSound() on a Dog object, it calls the overridden method in the Dog
class.
 This is method overriding, where a subclass provides a specific implementation of a
method already defined in its superclass.

Dynamic Method Dispatch (Runtime Polymorphism)

 Dynamic Method Dispatch, also known as Runtime Polymorphism, is a mechanism


in Java where a call to an overridden method is resolved at runtime, rather than
compile-time.
 This is achieved using method overriding and upcasting (where a parent class
reference variable refers to a child class object).

Example :

// Parent class
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}

// Child class overriding the makeSound() method


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

// Another child class


class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meows");
}
}

public class Main {


public static void main(String[] args) {
Animal myAnimal; // Parent class reference

myAnimal = new Dog(); // Upcasting: Parent reference to Dog object


myAnimal.makeSound(); // Calls Dog's makeSound() (Runtime Decision)
myAnimal = new Cat(); // Upcasting: Parent reference to Cat object
myAnimal.makeSound(); // Calls Cat's makeSound() (Runtime Decision)
}
}

Output:
Dog barks
Cat meows

Explanation:
1. Upcasting: We use a parent class reference (Animal myAnimal) to refer to different
child class objects (Dog, Cat).
2. Method Overriding: Each subclass (Dog, Cat) provides its own implementation of the
makeSound() method.
3. Runtime Resolution: The method that gets executed is determined at runtime based on
the actual object type (Dog or Cat), not the reference type (Animal).

Abstract class in Java


 A class that is declared with abstract keyword is known as abstract class in java.
 It can have abstract and non-abstract methods (method with body).
 It needs to be extended and its method implemented. It cannot be instantiated.

Example
abstract class
1. abstract class A{}
abstract method
1. abstract void printStatus();//no body and abstract
Example of abstract class that has abstract method
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
} output: running safely..
PACKAGES:

Java Package
 A java package is a group of similar types of classes, interfaces and sub-packages.
 Package in java can be categorized in two form,
 built-in package and
 user-defined package.
 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Example:

public class Simple{


public static void main(String args[])
{ System.out.println("Welcome to package");
}}
Interfaces :

An interface in Java is a blueprint for a class that contains only abstract methods (before Java 8) and
default/static methods (after Java 8).

🔹 Key Features of an Interface:


✔ Defines a set of methods that a class must implement
✔ Supports multiple inheritance (unlike classes)
✔ Helps in achieving abstraction
✔ Cannot have instance variables (only constants)

Syntax for interface


interface MyInterface {
// Abstract method (no implementation)
void display();
}

Interface vs Abstract Class

Feature Interface Abstract Class


Only abstract (default & static allowed in Can have both abstract & concrete
Methods
Java 8+) methods
Variables Only public static final (constants) Can have instance variables
Inheritance Supports multiple inheritance Only single inheritance
Constructor No constructors Can have constructors

Multiple Inheritance Using Interfaces


interface A {
void methodA();
}

interface B {
void methodB();
}

// Implementing multiple interfaces


class C implements A, B {
public void methodA() {
System.out.println("Method A implemented");
}

public void methodB() {


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

public class Main {


public static void main(String[] args) {
C obj = new C();
obj.methodA();
obj.methodB();
}
}
💡 Output

Method A implemented
Method B implemented

Real world example :


interface Payment {
void makePayment(double amount);
}

class CreditCard implements Payment {


public void makePayment(double amount) {
System.out.println("Payment of $" + amount + " made using Credit Card.");
}
}

class PayPal implements Payment {


public void makePayment(double amount) {
System.out.println("Payment of $" + amount + " made using PayPal.");
}
}
public class Main {
public static void main(String[] args) {
Payment p1 = new CreditCard();
p1.makePayment(100.50);

Payment p2 = new PayPal();


p2.makePayment(200.75);
}
}
💡 Output

Payment of $100.5 made using Credit Card.


Payment of $200.75 made using PayPal.

You might also like