Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PPT

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 36

----------:oops concept:----------

Inheritance:-

1. The process of acquiring fields(variables) and methods(behaviors) from one


class to another class is called inheritance.

2. The main objective of inheritance is code extensibility whenever we are


extending class automatically the code is reused.

3. In inheritance one class giving the properties and behavior & another class is
taking the properties and behavior

. 4. Inheritance is also known as is-a relationship. By using extends keyword we


are achieving inheritance concept.

5. extends keyword used to achieve inheritance & it is providing relationship


between two classes when you make relationship then able to reuse the code.

6. In java parent class is giving properties to child class and Child is acquiring
properties from Parent.

7. To reduce length of the code and redundancy of the code sun people
introduced inheritance concept.

Types of inheritance :-

There are five types of inheritance in java.

1. Single inheritance.

2. Multilevel inheritance.

3. Hierarchical inheritance.

4. Multiple inheritance(Not Support in java)

5. Hybrid Inheritance.
i) Single inheritance:-

One class has one and only one direct super class is called single inheritance.  In
the absence of any other explicit super class, every class is implicitly a subclass of
Object class.

Class B extends A ===>class B acquiring properties of A class.

Example:-
1) class Parent

void property()

System.out.println("money");

};

class Child extends Parent

void m1()

System.out.println("m1 method");

public static void main(String[] args)


{

Child c = new Child();

c.property(); //parent class method executed


c.m1(); //child class method executed

};

Example 2) 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...

3) public class Shape


{
int length;
int breadth;
}
public class Rectangle extends Shape
{
int area;
public void calcualteArea()
{
area = length*breadth;
}
public static void main(String args[])
{
Rectangle r = new Rectangle();
//Assigning values to Shape class attributes
r.length = 10;
r.breadth = 20;
//Calculate the area
r.calcualteArea();
System.out.println("The Area of rectangle of length \""
+r.length+"\" and breadth\""+r.breadth+"\"
is \""+r.area+"\"");
}
}
Output :

The Area of rectangle of length "10" and breadth "20"


is "200"

ii) Multilevel inheritance:-


One Sub class is extending Parent class then that sub class will become
Parent class of next extended class this flow is called multilevel inheritance.
Class B extends A ===> class B acquiring properties of A class Class C extends B
===> class C acquiring properties of B class [indirectly class C using properties of
A & B classes].

Example:-

1)class A

void m1()

System.out.println("m1 method");

};

class B extends A

void m2()

System.out.println("m2 method");

};

class C extends B
{

void m3()

System.out.println("m3 method");

public static void main(String[] args)

A a = new A();

a.m1();

B b = new B();

b.m1();

b.m2();;

C c = new C();

c.m1(); c.m2();

c.m3();

2) 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.eat();  
}}  

Output:

weeping...
barking...
eating...

iii) Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a


superclass (base class) for more than one sub class.In below image, the class A
serves as a base class for the derived class B,C and D.
Class B extends A ===> class B acquiring properties of A class

Class C extends A ===>class C acquiring properties of A class

Class D extends A ===>class D acquiring properties of A class

Example:- class A

void m1()

System.out.println("A class");

};
class B extends A

void m2()

System.out.println("B class");

};

class C extends A

void m2(){System.out.println("C class");

};

class Test

public static void main(String[] args)

B b= new B();

b.m1(); b.m2();

C c = new C();

c.m1();

c.m2();
}

};

File: TestInheritance3.java

EXAMPLE 2) 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...

iv) Multiple inheritance:-

Multiple Inheritance (Through Interfaces) : In Multiple inheritance ,one class can


have more than one superclass and inherit features from all parent classes. Please note
that Java does not support multiple inheritance with classes. In java, we can achieve
multiple inheritance only through Interfaces. In image below, Class C is derived from
interface A and B.

EXAMPLE 1) Class A extends B ===>valid Class

A extends B ,C ===>invalid

Example:-

class A

void money()

System.out.println("A class money");

};

class B

void money()

{
System.out.println("B class money");

};

class C extends A,B

public static void main(String[] args)

C c = new C();

c.money(); //which method executed A--->money() or B--->money

};

EXAMPLE 2)
class A{  
void msg()
{
System.out.println("Hello");
}  
}  
class B{  
void msg(){System.out.println("Welcome");
}  
}  
class C extends A,B{//suppose if it were  
   
 public static void main(String args[]){  
   C obj=new C();  
   obj.msg();//Now which msg() method would be invoked?  
}  
}  
Compile Time Error

v) Hybrid Inheritance(Through Interfaces) : It is a mix of two or more of the


above types of inheritance. Since java doesn’t support multiple inheritance with
classes, the hybrid inheritance is also not possible with classes. In java, we can
achieve hybrid inheritance only through Interfaces.

Example 1)

class C
{
public void disp()
{
System.out.println("C");
}
}

class A extends C
{
public void disp()
{
System.out.println("A");
}
}

class B extends C
{
public void disp()
{
System.out.println("B");
}

class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){

D obj = new D();


obj.disp();
}
}
Output:

Output:--D

2) Encapsulation in Java()
Encapsulation in Java is a process of wrapping code and data together into a single unit,
for example, a capsule which is mixed of several medicines.

We can create a fully encapsulated class in Java by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.

The Java Bean class is the example of a fully encapsulated class.

Advantage of Encapsulation in Java


By providing only a setter or getter method, you can make the class read-only or write-
only. In other words, you can skip the getter or setter methods.

It provides you the control over the data. Suppose you want to set the value of id which
should be greater than 100 only, you can write the logic inside the setter method. You can
write the logic not to store the negative numbers in the setter methods.

It is a way to achieve data hiding in Java because other class will not be able to access the
data through the private data members.

The encapsulate class is easy to test. So, it is better for unit testing.

The standard IDE's are providing the facility to generate the getters and setters. So, it
is easy and fast to create an encapsulated class in Java.
Examples:--i)

package com.datapoint;  
public class Student{  
//private data member  
private String name;  
//getter method for name  
public String getName(){  
return name;  
}  
//setter method for name  
public void setName(String name){  
this.name=name  
}  
}  

File: Test.java

//A Java class to test the encapsulated class.  
package com.datapoint;  
class Test{  
public static void main(String[] args){  
//creating instance of the encapsulated class  
Student s=new Student();  
//setting value in the name member  
s.setName("vijay");  
//getting value of the name member  
System.out.println(s.getName());  
}  
}  
Compile By: javac -d . Test.java
Run By: java com.datapoint.Test

Output:

vijay

Example ii)

class Account {  
//private data members  
private long acc_no;  
private String name,email;  
private float amount;  
//public getter and setter methods  
public long getAcc_no() {  
    return acc_no;  
}  
public void setAcc_no(long acc_no) {  
    this.acc_no = acc_no;  
}  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}  
public String getEmail() {  
    return email;  
}  
public void setEmail(String email) {  
    this.email = email;  
}  
public float getAmount() {  
    return amount;  
}  
public void setAmount(float amount) {  
    this.amount = amount;  
}  
  
}  

File: TestAccount.java

//A Java class to test the encapsulated class Account.  
public class TestEncapsulation {  
public static void main(String[] args) {  
    //creating instance of Account class  
    Account acc=new Account();  
    //setting values through setter methods  
    acc.setAcc_no(7560504000L);  
    acc.setName("Sonoo Jaiswal");  
    acc.setEmail("sonoojaiswal@datapoint.com");  
    acc.setAmount(500000f);  
    //getting values through getter methods  
    System.out.println(acc.getAcc_no()+" "+acc.getName()+" "+acc.getEmail()+" 
"+acc.getAmount());  
}  
}  

Output:

7560504000 Sonoo Jaiswal sonoojaiswal@datapoint.com 500000.0


Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It cannot
be instantiated.

Points to Remember

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.
Example of abstract class

1. abstract class A{}  

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an
abstract method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract  
Example of Abstract class that has an abstract method
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

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();  
}  
}  
running safely

Understanding the real scenario of Abstract class


In this example, Shape is the abstract class, and its implementation is provided by the
Rectangle and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the end user),
and an object of the implementation class is provided by the factory method.

A factory method is a method that returns the instance of the class. We will learn about
the factory method later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle
class will be invoked.

File: TestAbstraction1.java

abstract class Shape{  
abstract void draw();  
}  
//In real scenario, implementation is provided by others i.e. unknown by end user  
class Rectangle extends Shape{  
void draw(){System.out.println("drawing rectangle");}  
}  
class Circle1 extends Shape{  
void draw(){System.out.println("drawing circle");}  
}  
//In real scenario, method is called by programmer or user  
class TestAbstraction1{  
public static void main(String args[]){  
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getSh
ape() method  
s.draw();  
}  
}  
drawing circle

Another example of Abstract class in java


File: TestBank.java

abstract class Bank{    
abstract int getRateOfInterest();    
}    
class SBI extends Bank{    
int getRateOfInterest(){return 7;}    
}    
class PNB extends Bank{    
int getRateOfInterest(){return 8;}    
}    
    
class TestBank{    
public static void main(String args[]){    
Bank b;  
b=new SBI();  
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    
b=new PNB();  
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    
}}    
Rate of Interest is: 7 %
Rate of Interest is: 8 %

Abstract class having constructor, data member and


methods
An abstract class can have a data member, abstract method, method body (non-abstract
method), constructor, and even main() method.

File: TestAbstraction2.java

//Example of an abstract class that has abstract and non-abstract methods  
 abstract class Bike{  
   Bike(){System.out.println("bike is created");}  
   abstract void run();  
   void changeGear(){System.out.println("gear changed");}  
 }  
//Creating a Child class which inherits Abstract class  
 class Honda extends Bike{  
 void run(){System.out.println("running safely..");}  
 }  
//Creating a Test class which calls abstract and non-abstract methods  
 class TestAbstraction2{  
 public static void main(String args[]){  
  Bike obj = new Honda();  
  obj.run();  
  obj.changeGear();  
 }  
}  

bike is created
running safely..
gear changed

Rule: If there is an abstract method in a class, that class must be abstract.

class Bike12{  
abstract void run();  
}  
compile time error

Rule: If you are extending an abstract class that has an abstract method, you must either provide the
implementation of the method or make this class abstract.
Another real scenario of abstract class
The abstract class can also be used to provide some implementation of the interface. In
such case, the end user may not be forced to override all the methods of the interface.

Note: If you are beginner to java, learn interface first and skip this example.

interface A{  
void a();  
void b();  
void c();  
void d();  
}  
  
abstract class B implements A{  
public void c(){System.out.println("I am c");}  
}  
  
class M extends B{  
public void a(){System.out.println("I am a");}  
public void b(){System.out.println("I am b");}  
public void d(){System.out.println("I am d");}  
}  
  
class Test5{  
public static void main(String args[]){  
A a=new M();  
a.a();  
a.b();  
a.c();  
a.d();  
}}  

Output:I am a
I am b
I am c
I am d
Interface in Java

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.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are
public, static and final by default. A class that implements an interface must implement all
the methods declared in the interface.

Syntax:
1. interface <interface_name>{  
2.       
3.     // declare constant fields  
4.     // declare methods that abstract   
5.     // by default.  
6. }  
Polymorphism:--
If one task is performed by different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc.

i) Method Overloading in Java


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

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

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.

In this example, we are creating static methods so that we don't need to create instance for
calling methods.

1. class Adder{  
2. static int add(int a,int b){return a+b;}  
3. static int add(int a,int b,int c){return a+b+c;}  
4. }  
5. class TestOverloading1{  
6. public static void main(String[] args){  
7. System.out.println(Adder.add(11,11));  
8. System.out.println(Adder.add(11,11,11));  
9. }}  

Output:

22
33

2) Method Overloading: changing data type of arguments


In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double
arguments.

1. class Adder{  
2. static int add(int a, int b){return a+b;}  
3. static double add(double a, double b){return a+b;}  
4. }  
5. class TestOverloading2{  
6. public static void main(String[] args){  
7. System.out.println(Adder.add(11,11));  
8. System.out.println(Adder.add(12.3,12.6));  
9. }}  

Output:

22
24.9

Q) Why Method Overloading is not possible by changing the


return type of method only?
In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:

1. class Adder{  
2. static int add(int a,int b){return a+b;}  
3. static double add(int a,int b){return a+b;}  
4. }  
5. class TestOverloading3{  
6. public static void main(String[] args){  
7. System.out.println(Adder.add(11,11));//ambiguity  
8. }}  

Output:

Compile Time Error: method add(int,int) is already defined in class Adder

System.out.println(Adder.add(11,11)); //Here, how can java determine which sum()


method should be called?

Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler time
error if you declare the same method having same parameters.

Can we overload java main() method?


Yes, by method overloading. You can have any number of main methods in a class by
method overloading. But JVM calls main() method which receives string array as arguments
only. Let's see the simple example:
1. class TestOverloading4{  
2. public static void main(String[] args){System.out.println("main with String[]");}  
3. public static void main(String args){System.out.println("main with String");}  
4. public static void main(){System.out.println("main without args");}  
5. }  

Output:

main with String[]

Method Overloading and Type Promotion


One type is promoted to another implicitly if no matching datatype is found. Let's
understand the concept by the figure given below:

As displayed in the above diagram, byte can be promoted to short, int, long, float or double.
The short datatype can be promoted to int,long,float or double. The char datatype can be
promoted to int,long,float or double and so on.

Example of Method Overloading with TypePromotion


1. class OverloadingCalculation1{  
2.   void sum(int a,long b){System.out.println(a+b);}  
3.   void sum(int a,int b,int c){System.out.println(a+b+c);}  
4.   
5.   public static void main(String args[]){  
6.   OverloadingCalculation1 obj=new OverloadingCalculation1();  
7.   obj.sum(20,20);//now second int literal will be promoted to long  
8.   obj.sum(20,20,20);  
9.   
10.   }  
11. }  
Output:40
60

Example of Method Overloading with Type Promotion if


matching found
If there are matching type arguments in the method, type promotion is not performed.

1. class OverloadingCalculation2{  
2.   void sum(int a,int b){System.out.println("int arg method invoked");}  
3.   void sum(long a,long b){System.out.println("long arg method invoked");}  
4.   
5.   public static void main(String args[]){  
6.   OverloadingCalculation2 obj=new OverloadingCalculation2();  
7.   obj.sum(20,20);//now int arg sum() method gets invoked  
8.   }  
9. }  
Output:int arg method invoked

Example of Method Overloading with Type Promotion in case of


ambiguity
If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.

1. class OverloadingCalculation3{  
2.   void sum(int a,long b){System.out.println("a method invoked");}  
3.   void sum(long a,int b){System.out.println("b method invoked");}  
4.   
5.   public static void main(String args[]){  
6.   OverloadingCalculation3 obj=new OverloadingCalculation3();  
7.   obj.sum(20,20);//now ambiguity  
8.   }  
9. }  
Output:Compile Time Error

ii) Method Overriding in Java


1. Understanding the problem without method overriding
2. Can we override the static method
3. Method overloading vs. method overriding

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).
Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method
overriding.

1. //Java Program to demonstrate why we need method overriding  
2. //Here, we are calling the method of parent class with child  
3. //class object.  
4. //Creating a parent class  
5. class Vehicle{  
6.   void run(){System.out.println("Vehicle is running");}  
7. }  
8. //Creating a child class  
9. class Bike extends Vehicle{  
10.   public static void main(String args[]){  
11.   //creating an instance of child class  
12.   Bike obj = new Bike();  
13.   //calling the method with child class instance  
14.   obj.run();  
15.   }  
16. }  

Output:

Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass that
is why we use method overriding.

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent
class but it has some specific implementation. The name and parameter of the method are
the same, and there is IS-A relationship between the classes, so there is method overriding.

1. //Java Program to illustrate the use of Java Method Overriding  
2. //Creating a parent class.  
3. class Vehicle{  
4.   //defining a method  
5.   void run(){System.out.println("Vehicle is running");}  
6. }  
7. //Creating a child class  
8. class Bike2 extends Vehicle{  
9.   //defining the same method as in the parent class  
10.   void run(){System.out.println("Bike is running safely");}  
11.   
12.   public static void main(String args[]){  
13.   Bike2 obj = new Bike2();//creating object  
14.   obj.run();//calling method  
15.   }  
16. }  

Output:
Bike is running safely

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. }  
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Can we override static method?


No, a static method cannot be overridden. It can be proved by runtime polymorphism, so
we will learn it later.

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