5th chapter- Methods and Classes
Download
Report
Transcript 5th chapter- Methods and Classes
Methods and Classes
Method Overloading
Two or more methods within the same class that share the
same name but different parameters
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
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);
}
}
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
o By changing number of arguments
o By changing the data type
Method Overloading
Java’s automatic type conversions
Method parameter match need not always be exact. In some
cases, Java’s automatic type conversions can apply in
overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i); // this will invoke test(double)
ob.test(123.2); // this will invoke test(double)
}
}
Output:
No parameters
a and b: 10 20
Inside test(double) a: 88
Inside test(double) a: 123.2
Method Overloading by changing the
number of arguments
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int
c){System.out.println(a+b+c);}
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Method Overloading by changing data type
of argument
class Calculation2{
void sum(int a,int b){
System.out.println(a+b);
}
void sum(double a,double b){
System.out.println(a+b);
}
public static void main(String args[]){
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
Method Overloading
Why Method Overloaing is not possible by changing only the
return type of method?
In java, method overloading is not possible by changing the return type of the
method because there may occur ambiguity. Let's see how ambiguity may
occur: because there was problem:
class Calculation3{
int sum(int a,int b){System.out.println(a+b); return (a+b);}
double sum(int a,int b){System.out.println(a+b); return (a+b);}
public static void main(String args[]){
Calculation3 obj=new Calculation3();
int result=obj.sum(20,20); //Compile Time Error
}
}
int result=obj.sum(20,20); //Here how can java determine which sum()
method should be called
Method Overloading with Type
Promotion
class OverloadingCalculation1{
void sum(int a,long b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
}
}
Output:40 60
Method Overloading with Type
Promotion in case ambiguity
class OverloadingCalculation3{
void sum(int a,long b){System.out.println("a method invoked");}
void sum(long a,int b){System.out.println("b method invoked");}
public static void main(String args[]){
OverloadingCalculation3 obj=new OverloadingCalculation3();
obj.sum(20,20);//now ambiguity
}
}
Output:Compile Time Error
Method Overloading with Type
Promotion if matching found
class OverloadingCalculation2{
void sum(int a,int b){System.out.println("int arg method invoked");}
void sum(long a,long b){System.out.println("long arg method invoked");}
public static void main(String args[]){
OverloadingCalculation2 obj=new OverloadingCalculation2();
obj.sum(20,20);//now int arg sum() method gets invoked
}
}
Output:int arg method invoked
Method Overloading
Method Overloading
Polymorphism
Runtime Polymorphism
Runtime polymorphism or Dynamic Method
Dispatch is a process in which a call to an overridden
method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the
reference variable of a superclass. The determination of the
method to be called is based on the object being referred to
by the reference variable.
Upcasting for Runtime Polymorphism
When reference variable of Parent class refers to the object
of Child class, it is known as upcasting. For example:
class A{}
class B extends A{}
--------------------------------A a = new B();//upcasting
Example of Runtime Polymorphism
Since method invocation is determined by the JVM not
compiler, it is known as runtime polymorphism.
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b = new Splender();//upcasting
b.run();
}
}
Output:
running safely with 60km.
Example of Runtime Polymorphism
method overriding but there was no upcasting
class Bank{
int getRateOfInterest(){return 0;}
}
class A extends Bank{
int getRateOfInterest(){return 8;}
}
class B extends Bank{
int getRateOfInterest(){return 7;}
}
class C extends Bank{
int getRateOfInterest(){return 9;}
}
class Test3{
public static void main(String args[]){
Bank b1=new A();
Bank b2=new B();
Bank b3=new C();
System.out.println(“A Rate of Interest: "+b1.getRateOfInterest());
System.out.println(“B Rate of Interest: "+b2.getRateOfInterest());
System.out.println(“C Rate of Interest: "+b3.getRateOfInterest());
}
}
Output:
A Rate of Interest: 8
B Rate of Interest: 7
C Rate of Interest: 9
Runtime Polymorphism with data member
Method is overridden not the datamembers, so runtime polymorphism can't be
achieved by data members.
In the example we are accessing the data member by Parent reference variable
which refers to the subclass object. Since we are accessing the data member
which is not overridden, hence it will access the data member of Parent class
always
class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;
public static void main(String args[]){
Bike obj=new Honda3();
System.out.println(obj.speedlimit);//90
}
Output:
90
Runtime Polymorphism with Multilevel
Inheritance
class Animal{
void eat(){System.out.println("eating");}
}
class Dog extends Animal{
void eat(){System.out.println("eating fruits");}
}
class BabyDog extends Dog{
void eat(){System.out.println("drinking milk");}
public static void main(String args[]){
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}
Output: eating
eating fruits
drinking Milk
Method Overriding
If subclass (child class) has the same method as declared in
the parent class, it is known as method overriding
Usage of Java Method Overriding
Method overriding is used to provide specific
implementation of a method that is already provided by its
super class.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
method must have same name as in the parent class
method must have same parameter as in the parent class.
must be IS-A relationship (inheritance).
Example of method overriding
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
}
Output:
Bike is running safely
Example of method overriding
class Bank{
int getRateOfInterest(){return 0;}
}
class A extends Bank{
int getRateOfInterest(){return 8;}
}
class B extends Bank{
int getRateOfInterest(){return 7;}
}
class C extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
A s=new A();
B i=new B();
C a=new C();
System.out.println(“A Rate of Interest: "+s.getRateOfInterest());
System.out.println(“B Rate of Interest: "+i.getRateOfInterest());
System.out.println(“C Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
A Rate of Interest: 8
B Rate of Interest: 7
C Rate of Interest: 9
method overriding
Can we override static method?
No, static method cannot be overridden.
Why we cannot override static method?
because static method is bound with class whereas instance
method is bound with object. Static belongs to class area and
instance belongs to heap area.
Can we override java main method?
No, because main is a static method.
Method Overriding
Method Overriding
Polymorphism
Difference between method Overloading
and Method Overriding
No.
Method Overloading
Method Overriding
1)
Method overloading is used to increase the readability
of the program.
Method overriding is used to provide the specific
implementation of the method that is already
provided by its super class.
2)
Method overloading is performed within class.
Method overriding occurs in two classes that have
IS-A (inheritance) relationship.
3)
In case of method overloading, parameter must be
different.
In case of method overriding, parameter must be
same.
4)
Method overloading is the example of compile time
polymorphism.
Method overriding is the example of run time
polymorphism.
5)
In java, method overloading can't be performed by
changing return type of the method only. Return type
Return type must be same or covariant in method
can be same or different in method overloading. But you overriding.
must have to change the parameter.
Overloading Constructors
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
}
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
Box() {
width = -1;
height = -1;
depth = -1;
}
}
Box ob = new Box();
Box ob = new Box();
Objects as Parameters
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
boolean TestEqualTo(Test obj) {
if(obj.a == a && obj.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.TestEqualTo(ob2));
System.out.println("ob1 == ob3: " + ob1.TestEqualTo(ob3));
}
}
Output:
ob1 == ob2: true
ob1 == ob3: false
Passing Parameters
Passing Parameters are two types:
call-by-value
call-by-reference
call-by-value
The call by value method of passing arguments to a function copies the actual
value of an argument into the formal parameter of the function.
In this case, changes made to the parameter inside the function have no effect
on the argument
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " + a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);
}
}
Output:
a and b before call: 15 20
a and b after call: 15 20
call-by-reference
The call by reference method of passing arguments to a function copies the address of
an argument into the formal parameter.
Inside the function, the address is used to access the actual argument used in the call. It
means the changes made to the parameter affect the passed argument.
class Test {
int a, b;
Test(int i, int j) {
a = i;
Output:
b = j;
ob.a and
}
ob.a and
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class PassObjRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
}
ob.b before call: 15 20
ob.b after call: 30 10
call-by-value & call-by-reference
When a simple type (primitive type variable) is passed to a
method, it is done by use of call-by-value.
Object are passed by use of call-by-reference
Returning Objects
A method can return any type of data, including class types
that is object
// Returning an object.
class Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
}
Output:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "
+ ob2.a);
}
}
Recursion
A method that calls itself is said to be recursive
// A simple example of recursion.
class Factorial {
// this is a recursive method
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
Output:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Nested/ Inner Class
class within another class known as nested classe
The scope of a nested class is bounded by the scope of its
enclosing/ outer class
it can access all the members of outer class including private
data members and methods
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Nested/ Inner Class
It is important to realize that an instance of Inner can be
created only in the context of class Outer
Inner is known only within the scope of class Outer
Advantage of inner classes
Three advantages of inner classes :
1) 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.
Nested/ Inner Class
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
OUTPUT:
// this is an inner class
display: outer_x = 100
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
Nested/ Inner Class
What is the difference between nested class and
inner class?
Ans: Inner class is a part of nested class.
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.
Non-static nested class(inner class)
a)Member inner class
b)Annomynous inner class
c)Local inner class
Static nested class
Member inner class
A non-static class that is created inside a class but outside a
method is called member inner class.
class Outer{
//code
class Inner{
//code
}
}
we are creating msg() method in member
inner class that is accessing the private data
member of outer class.
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Anonymous inner class
A class that have no name is known as anonymous inner class
in java. It should be used if you have to override method of
class or interface. Java Anonymous inner class can be created
by two ways:
Class (may be abstract or concrete).
Interface
Anonymous inner class example
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
Anonymous inner class example
Internal working of given code
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
A class is created but its name is decided by the compiler which extends the
Person class and provides the implementation of the eat() method.
An object of Anonymous class is created that is referred by p reference variable
of Person type.
Internal class generated by the compiler
import java.io.PrintStream;
static class TestAnonymousInner$1 extends Person
{
TestAnonymousInner$1(){}
void eat()
{
System.out.println("nice fruits");
}
}
Java Local inner class
A class i.e. created inside a method is called local inner class
//Java local inner class example
//Example of local inner class with local variable
public class localInner1{
private int data=30;//instance variable
void display(){
class Local{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
localInner1 obj=new localInner1();
obj.display();
}
}
class localInner2{
private int data=30;//instance variable
void display(){
int value=50;//local variable must be final till jdk 1.7 only
class Local{
void msg(){System.out.println(value);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
localInner2 obj=new localInner2();
obj.display();
}
}
Static inner class
A static class i.e. created inside a class is called static nested class in java. It
cannot access non-static data members and methods. It can be accessed by outer
class name.
It can access static data members of outer class including private.
Static nested class cannot access non-static (instance) data member or method.
//static nested class example with instance method
//static nested class example with static method
classTestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=newTestOuter1.Inner();
obj.msg();
}
}
classTestOuter2{
static int data=30;
static class Inner{
static void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
();//no need to create the instance of static nesTestOuter2.I
nner.msgted class
}
}
Java Programs