0% found this document useful (0 votes)
8 views27 pages

Unit2_first half

Method overloading in Java allows a class to have multiple methods with the same name but different parameters, enhancing code readability. It can be achieved by changing the number of arguments or the data type of arguments, but not solely by changing the return type. The document also covers object parameters, returning objects, and different types of classes including inner, nested, and anonymous classes, as well as inheritance concepts such as single, multiple, and multi-level inheritance.

Uploaded by

anuja.it
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)
8 views27 pages

Unit2_first half

Method overloading in Java allows a class to have multiple methods with the same name but different parameters, enhancing code readability. It can be achieved by changing the number of arguments or the data type of arguments, but not solely by changing the return type. The document also covers object parameters, returning objects, and different types of classes including inner, nested, and anonymous classes, as well as inheritance concepts such as single, multiple, and multi-level inheritance.

Uploaded by

anuja.it
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/ 27

Method Overloading in Java

Definition:

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In Java, Method Overloading is not possible by changing the return type of the method only.

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two numbers and
second add method performs addition of three numbers.

class Addition
{
void add(int a,int b)
{
System.out.println("sum of a and b is "+(a+b));

}
void add(int a,int b,int c)
{
System.out.println("sum of a and b and c is "+(a+b+c));

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

Addition obj=new Addition();


obj.add(2,3);
obj.add(3,4,5);
}
} Test it Now

Output:
sum of a and b is 5
sum of a and b is7b is 7

2) Method Overloading: changing data type of arguments

class Addition
{
void add(int a,int b)
{
System.out.println("sum of a and b is "+(a+b));

}
void add(double a,double b)
{
System.out.println("sum of a and b is "+(a+b));
}
public static void main(String[] args)
{
Addition obj=new Addition();
obj.add(2,3);
obj.add(3.4,4.2);
}
} Test it NowOutput:
sum of a and b is 5
sum of a and b is 7.

Object as Parameters

Object as an argument is use to establish communication between two or


more objects of same class as well as different class

class Add
{
int a;
int b;

Add(int x,int y)// parametrized constructor


{
a=x;
b=y;
}
void sum(Add A1) // object 'A1' passed as parameter in function 'sum'
{
int sum1=A1.a+A1.b;
System.out.println("Sum of a and b :"+sum1);
}
}

public class classExAdd


{
public static void main(String arg[])
{
Add A=new Add(5,8);
/* Calls the parametrized constructor
with set of parameters*/
A.sum(A);
}}

Output

Sum of a and b :13

Returning Objects:

A method can return any type of data, including class types that you create. For example, in the
following program, the incrByTen( ) method returns an object in which the value of a is ten greater than
it is in the invoking object.

The output generated by this program is shown here:


ob1.a: 2

ob2.a: 12

ob2.a after second increase: 22

As you can see, each time incrByTen( ) is invoked, a new object is created, and a reference to it is
returned to the calling routine.

Static,Nested and Inner Class:


Inner Class
The classes that are non-static and nested are called Inner Class.
Note:
We cannot create an instance of inner class without creating an instance
of outer class.

1. class TestMemberOuter1{
2. private int data=30;
3. class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestMemberOuter1 obj=new TestMemberOuter1();
8. TestMemberOuter1.Inner in=obj.new Inner();
9. in.msg();
10. }
11. }

Output:

data is 30

Nested Class
Java allow us to define a class within a class known as Nested
Class.
It may be static or non-static.
The major difference between static and non-static class
1.The static and non-static members of an outer class can be
accessed by an inner class.
2.The static members of the outer class can be accessed only by
the static class.
Types of Nested Class

 Static Nested Classes


 Non-static Nested Classes (or Inner Classes) We can further divide the Non-static Classes into -
o Member Inner Classes
o Local Inner Classes
o Anonymous Inner Classes

Static Nested Class


• We can declare a class static using the static keyword .
• A class be declared static only if it is a nested class.
• The property of static class is that it does not allow us to
access non-static member of the outer class.
• class TestOuter1{
• static int data=30;
• static class Inner{
• void msg(){System.out.println("data is "+data);}
• }
• public static void main(String args[]){
• TestOuter1.Inner obj=new TestOuter1.Inner();
• obj.msg();
• }
• }

Output:

data is 30

In this example, you need to create the instance of static nested class
because it has instance method msg(). But you don't need to create the
object of the Outer class because the nested class is static and static
properties, methods, or classes can be accessed without an object.

Non-static Nested Classes


Type Description

Member Inner A class created within class and outside method.


Class

Anonymous A class created for implementing an interface or


Inner Class extending class. The java compiler decides its name.

Local Inner A class was created within the method.


Class

Java Member Inner class


A non-static class that is created inside a class but outside a method is
called member inner class. It is also known as a regular inner class. It
can be declared with access modifiers like public, default, private, and
protected.

Syntax:

1. class Outer{
2. //code
3. class Inner{
4. //code
5. }
6. }

Java Member Inner Class Example


In this example, we are creating a msg() method in the member inner class
that is accessing the private data member of the outer class.

TestMemberOuter1.java

1. class TestMemberOuter1{
2. private int data=30;
3. class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestMemberOuter1 obj=new TestMemberOuter1();
8. TestMemberOuter1.Inner in=obj.new Inner();
9. in.msg();
10. }
11.}
Test it Now

Output:

data is 30

Java Anonymous inner class


Java anonymous inner class is an inner class without a name and for which
only a single object is created. An anonymous inner class can be useful when
making an instance of an object with certain "extras" such as overloading
methods of a class or interface, without having to actually subclass a class.

In simple words, a class that has no name is known as an anonymous inner


class in Java. It should be used if you have to override a method of class or
interface. Java Anonymous inner class can be created in two ways:

1. Class (may be abstract or concrete).


2. Interface

Java anonymous inner class example using class


TestAnonymousInner.java

1. abstract class Person{


2. abstract void eat();
3. }
4. class TestAnonymousInner{
5. public static void main(String args[]){
6. Person p=new Person(){
7. void eat(){System.out.println("nice fruits");}
8. };
9. p.eat();
10. }
11.}
Test it Now

Output:

nice fruits

Java Local inner class


A class i.e., created inside a method, is called local inner class in java. Local
Inner Classes are the inner classes that are defined inside a block. Generally,
this block is a method body. Sometimes this block can be a for loop, or an if
clause. Local Inner classes are not a member of any enclosing classes. They
belong to the block they are defined within, due to which local inner classes
cannot have any access modifiers associated with them. However, they can
be marked as final or abstract. These classes have access to the fields of the
class enclosing it.

If you want to invoke the methods of the local inner class, you must
instantiate this class inside the method.

Java local inner class example


LocalInner1.java

1. public class localInner1{


2. private int data=30;//instance variable
3. void display(){
4. class Local{
5. void msg(){System.out.println(data);}
6. }
7. Local l=new Local();
8. l.msg();
9. }
10. public static void main(String args[]){
11. localInner1 obj=new localInner1();
12. obj.display();
13. } }
Test it Now

Output:

30

Inheritance:
Definition1:

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

Definition2:

The process of deriving new from existing class by sharing the properties of existing class is
known as inheritance.

The new class that is created is known as subclass (child or derived class) and the existing class from where the
child class is derived is known as superclass (parent or base class).

Why use inheritance in java

o For Code Reusability

The syntax of Java Inheritance

o class Subclass-name extends Superclass-name


o {
o //methods and fields
o }

Inheritance Basics
Member Access and Inheritance

Although a subclass includes all of the members of its superclass, it cannot access those members of the
superclass that have been declared as private.
Types of Inheritance’

1.Single

2.Multiple

3.Multilevel
4.hierarchial

5.hybrid

Single Inheritance

Deriving a new class from single parent class

class A
{
int a, b;
void display()
{
System.out.println(“Inside class A values =”+a+” ”+b);
}
}
class B extends A
{
int c;
void show()
{
System.out.println(“Inside Class B values=”+a+” “+b+” “+c); }
}
class SingleInheritance
{
public static void main(String args[])
{
B obj = new B(); //derived class object
obj.a=10;
obj.b=20;
obj.c=30;
obj.display();
obj.show();
}
}
Output:

Example:2

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Test it Now

Programmer salary is:40000.0


Bonus of programmer is:10000

Multiple Inheritance

Deriving a new class from more than one base class

Interface:

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. 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 cannot have a method
body.
Syntax:

1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

Example:
interface A
{
public abstract void execute1();
}
interface B
{
public abstract void execute2();
}
class C implements A,B
{
public void execute1()
{
System.out.println("Haii.. I am from execute1");
}
public void execute2()
{
System.out.println("Haii.. I am from execute2");
}
}
public class Main
{
public static void main(String[] args)
{
C obj = new C();
obj.execute1();
obj.execute2();
}
}
Output:
Haii.. I am from execute1
Haii.. I am from execute2
Example:2
interface MotorBike
{
int speed=50;
public void totalDistance();
}
interface Cycle
{
int distance=150;
public void speed();
}
public class TwoWheeler implements MotorBike,Cycle
{
int totalDistance;
int avgSpeed;
public void totalDistance()
{
totalDistance=speed*distance;
System.out.println("Total Distance Travelled :
"+totalDistance);
}
public void speed()
{
int avgSpeed=totalDistance/speed;
System.out.println("Average Speed maintained : "+avgSpeed);
}
public static void main(String args[])
{
TwoWheeler t1=new TwoWheeler();
t1.totalDistance();
t1.speed();
}
}
Output

Total Distance Travelled : 7500

Average Speed maintained : 150

Multi-level Inheritance

class Shape {
public void display() {
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
}
}
class Cube extends Rectangle {
public void volume() {
System.out.println("Inside volume");
}}
public class Tester {
public static void main(String[] arguments) {
Cube cube = new Cube();
cube.display();
cube.area();
cube.volume();
}}

Output

Inside display
Inside area
Inside volume

Example:
class Car{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{

public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output:

Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph

Hierarchial Inheritance

class A {
public void print_A() { System.out.println("Class A"); }
}
class B extends A {
public void print_B() { System.out.println("Class B"); }
}
class C extends A {
public void print_C() { System.out.println("Class C"); }
}
class D extends A {
public void print_D() { System.out.println("Class D"); }
}
// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
C obj_C = new C();
obj_C.print_A();
obj_C.print_C();
D obj_D = new D();
obj_D.print_A();
obj_D.print_D();
}}
Output
Class A
Class B
Class A
Class C
Class A
Class D
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.

1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent
class. It is used if parent class and child class have same fields.

1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}
Output:
black
white

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should
be used if subclass contains the same method as parent class. In other
words, it is used if method is overridden.

class Person {
void message()
{
System.out.println("This is person class\n");
}}
// Subclass Student
class Student extends Person {
void message()
{
System.out.println("This is student class");
}
// Note that display() is
// only in Student class
void display()
{
// will invoke or call current
// class message() method
message();
// will invoke or call parent
// class message() method
super.message();
}}
// Driver Program
class Test {
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}}
Output
This is student class
This is person class

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor.
Let's see a

// Java Code to show use of


// super keyword with constructor

// superclass Person
class Person {
Person()
{
System.out.println("Person class Constructor");
}
}

// subclass Student extending the Person class


class Student extends Person {
Student()
{
// invoke or call parent class constructor
super();

System.out.println("Student class Constructor");


}
}
// Driver Program
class Test {
public static void main(String[] args)
{
Student s = new Student();
}
}
Output
Person class Constructor
Student class Constructor

Another example of super keyword where super() is provided by the


compiler implicitly.

1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. System.out.println("dog is created");
7. }
8. }
9. class TestSuper4{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. }}
Output:

animal is created
dog is created

super example: real use

Let's see the real use of super keyword. Here, Emp class inherits Person
class so all the properties of Person will be inherited to Emp by default. To
initialize all the property, we are using parent class constructor from child
class. In such way, we are reusing the parent class constructor.

1. class Person{
2. int id;
3. String name;
4. Person(int id,String name){
5. this.id=id;
6. this.name=name;
7. }
8. }
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constructor
13. this.salary=salary;
14. }
15. void display(){System.out.println(id+" "+name+" "+salary);}
16. }
17. class TestSuper5{
18. public static void main(String[] args){
19. Emp e1=new Emp(1,"ankit",45000f);
20. e1.display();
21. }}
Test it Now

Output:

1 ankit 45000
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.

In other words, If a subclass provides the specific implementation of


the method that has been declared by one of its parent class, it is
known as method overriding.

Usage of Java Method Overriding

o Method overriding is used to provide the specific implementation of a


method which is already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


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

A real example of Java Method Overriding

Consider a scenario where Bank is a class that provides functionality to get


the rate of interest. However, the rate of interest varies according to banks.
For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of
interest.

Java method overriding is mostly used in Runtime Polymorphism which we will learn in
next pages.
1. //Java Program to demonstrate the real scenario of Java Method Overriding
2. //where three classes are overriding the method of a parent class.
3. //Creating a parent class.
4. class Bank{
5. int getRateOfInterest(){return 0;}
6. }
7. //Creating child classes.
8. class SBI extends Bank{
9. int getRateOfInterest(){return 8;}
10. }
11.
12. class ICICI extends Bank{
13. int getRateOfInterest(){return 7;}
14. }
15. class AXIS extends Bank{
16. int getRateOfInterest(){return 9;}
17. }
18. //Test class to create objects and call the methods
19. class Test2{
20. public static void main(String args[]){
21. SBI s=new SBI();
22. ICICI i=new ICICI();
23. AXIS a=new AXIS();
24. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
25. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
26. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
27. }
28. }
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Difference between Method Overloading and Method Overriding


Can we override static method?

No, a static method cannot be overridden. It can be proved by runtime


polymorphism,

Why can we not override static method?

It is because the static method is bound with class whereas instance method
is bound with an object. Static belongs to the class area, and an instance
belongs to the heap area.

Can we override java main method?

No, because the main is a static method.

You might also like