Unit2_first half
Unit2_first half
Definition:
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
In Java, Method Overloading is not possible by changing the return type of the method only.
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)
{
Output:
sum of a and b is 5
sum of a and b is7b is 7
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
class Add
{
int a;
int b;
Output
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.
ob2.a: 12
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.
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
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.
Syntax:
1. class Outer{
2. //code
3. class Inner{
4. //code
5. }
6. }
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
Output:
nice fruits
If you want to invoke the methods of the local inner class, you must
instantiate this class inside the method.
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).
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
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
Multiple Inheritance
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
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
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
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
The super keyword can also be used to invoke the parent class constructor.
Let's see a
// superclass Person
class Person {
Person()
{
System.out.println("Person class Constructor");
}
}
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
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.
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
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.