0% found this document useful (0 votes)
18 views

Unit 4 Notes

Uploaded by

bhagwatgayal4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Unit 4 Notes

Uploaded by

bhagwatgayal4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Unit IV

Inheritance and Polymorphism

Inheritance: Introduction, Need of Inheritance, Types of Inheritance, Benefits of Inheritance,


Cost of Inheritance, Constructors in derived Classes, Method Overriding, and Abstract
Classes and Interfaces. Polymorphism and Software Reuse: Introduction, Types of
Polymorphism (Compile Time and RunTime Polymorphism), Mechanisms for
Software Reuse, Efficiency and Polymorphism.

Inheritance – results from deriving new classes from existing classes Root Class –
all java classes are derived from the java.lang.Object class

GeometricObject1
GeometricObject ` Superclass
-color:
-color:String
String (object) Parent Class
-fllled: boolean (color) Base Class
-dateCreated:
-fllled: booleanjava.util.Date
-dateCreated: java.util.Date
+GeometricObject( )
+getColor( ): String
+setColor(color: String ): void
+GeometricObject( )
+isFilled( ): boolean
+setFilled(filled: boolean): void
+getColor( ): String
+getDateCreated( ): java.util.Date
+toString( ): String
+setColor(color: String ): void
+isFilled( ): boolean Subclass Child
+setFilled(filled: boolean): void Class Derived
Class
+getDateCreated( ): java.util.Date Extended Class
+toString( ): String

Circle4 Rectangle1
-radius: double -width: double
-height: double
+Circle( )
+Circle(radius: double) +Rectangle( )
+getRadius( ): double +Rectangle(width: double, height: double)
+setRadius(radius: double): void +getWidth( ): double
+getArea( ): double +setWidth(width: double): void
+getParimeter( ): double +getHeight( ): double
+getDiameter( ): double +setHeight(height: double): void
+printCircle( ): void +getArea( ): double
+getPerimeter( ): double

A child class inherits all accessible data fields and methods from its parent class! A child
class does not inherit the constructors of the parent class!
The child class may also add uniquely new data fields and methods!
1. Implementation

a. GeometricObject1.java

public class GeometricObject1


{
private String color = “white”;
private boolean filled;

private java.util.Date dateCreated;

public GeometricObject1( ) { dateCreated = new java.util.Date( ); } public String

getColor( ) { return color; }

public void setColor(String color) { this.color = color;} public

boolean isFilled( ) { return filled; }

public void setFilled(boolean filled) { this.filled = filled; } public

java.util.Date getDateCreated( ) { return dateCreated; }

public String toString( ) { return “created on “ + dateCreated

+ “\ncolor: “ + color + “ and filled: “ + filled; }


}

b. Circle4.java

public class Circle4 extends GeometricObject1


{
private double radius;

public Circle4( ) { }
public Circle4(double radius ) { this.radius = radius; }

public double getRadius( ) { return radius; }


public void setRadius( double radius) { this.radius = radius; }

public double getArea( ) { return radius * radius * Math.PI; } public


double getDiameter( ) { return 2 * radius; }

public double getPerimeter( ) { return 2 * radius * Math.PI; }


public void printCircle( )
{
System.out.println(“The circle is created “ + getDateCreated( ) + “ and the
radius is “ + radius);

}
c. Rectangle1.java

public class Retangle1 extends GeometricObject1


{
private double width; private
double height;

public Rectangle1( ) { }
public Rectangle1(double width, double height )
{
this width = width; this
height = height;
}

public double getWidth( ) { return width; }


public void setWidth(double width) { this width = width; }

public double getHeight( ) { return height; }


public void setHeigth(double height) { this height = height; }

public double getArea( ) { return width * height: }


public double getPerimeter( ) { return 2 * (width + height); }
}

d. TestCircleRectangle.java

public class TestCircleRetangle


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

Circle4 circle = new Circle4(1); System.out.println(


circle.toString( )); System.out.println( circle.getRadius(
)); System.out.println(circle.getArea( ) ); See Liang page 334 for output of
System.out.println( circle.getDiameter( )); TestCircleRectangle.java

Rectangle1 rectangle = new Rectangle1(2,4); System.out.println(


rectangle.toString( )); System.out.println(rectangle.getArea( ) );
System.out.println( rectangle.getPerimeter( ));
}
}
Remark: A subclass is NOT a subset of its superclass; in fact, since the subclass has access
to more items than the superclass, an instance of the superclass can be thought
of as a subset of an instance of the subclass!

Remark: Inheritance is used to model is-a relationships; e.g., an apple is a fruit! For a class
B to extend a class A, class B should contain more detailed information than
class A.
A subclass and a superclass must have an is-a relationship

Remark: C++ allows inheritance from multiple classes; i.e., it supports multiple
inheritance.
Remark: Java does not allow inheritance from multiple classes; a Java class may inherit
directly only from one superclass, i.e., the restriction is known as single
inheritance. If the extends keyword is used to define a subclass, it allows only
one parent class. Multiple inheritance in java is achieved by the use of interfaces.

2. Constructor Chaining

A child class inherits all accessible data fields and methods from its parent class,
BUT the child class does not inherit the constructors of the parent class!

“this” keyword – refers to the calling object – self-referential

“super” keyword – refers to the parent of the calling object – used to

o call a superclass constructor


 super( ) invokes the no-arg constructor of its superclass
 super(argument list) invokes the superclass constructor that
matches the argument list
 the call for a superclass constructor must be the first statement in
the subclass constructor
 invoking a superclass constructor name in a subclass causes a
syntax error
 if a subclass does not explicitly invoke its superclass constructor, the
compiler places the “super( )” statement as the first line in the
subclass constructor, i.e.,

public A( ){ } public A( ){ super( ); }


keyword

public class Faculty extends Employee


{ Key
public static void main(String[ ] args) Constructor Calls
{
new Faculty( );
Constructor Returns
}

public Faculty( )
{

System.out.println(“(4) Faculty no-arg constructor invoked”);


}
}

class Employee extends Person


{

public Employee( )
{
this(“(2) Employee’s overloaded constructor invoked”); System.out.println(“(3)
Employee’s no-arg constructor invoked”);
}

public Employee( String s )


{
System.out.println(s);
}
}

class Person
{
public Person( )
{
System.out.println(“(1) Person’s no-arg constructor invoked”);
}
}

Construction of the Faculty


Object

The Parent Constructor is


Faculty Constructor (4)

Employee Constructor (3)

Employee Constructor (2)

Person Constructor (1)


Since the Apple class does not have
any constructors, a no- arg
public class Apple extends Fruit
constructor is implicitly declared.
{
public Apple( ){ }
The Apple no-arg constructor
automatically invokes the Fruit no-
} arg constructor; but Fruit does not
have a no-arg constructor. But
since Fruit has an explicitly
class Fruit declared constructor with a
{ parameter, i.e.,

public Fruit(String name),


public Fruit(String name)
then the complier cannot implicitly
{ invoke a no-arg constructor.

System.out.println(Fruit constructor is invoked”);


} Hence, an Apple object cannot be
created and the program cannot be
} compiled!

Best Practices

PROVIDE EVERY CLASS WITH A NO-ARG CONSTRUCTOR


SUCH A POLICY AIDS THE EXTENSION OF THE CLASS, I.E.,
IT AVOIDS THE ERROR DELINEATED ABOVE
3. Overriding Methods

“super” keyword is also used to call a superclass method subclasses


inherit methods from their superclasses
a subclass may modify the definition of an inherited method for use in that subclass –
method overriding

public class GeometricObject1

{
private String color = “white”; private
boolean filled;

private java.util.Date dateCreated;


public GeometricObject1( ) { dateCreated = new java.util.Date( ); } public
String getColor( ) { return color; }

public void setColor(String color) { this.color = color;} public


boolean isFilled( ) { return filled; }

public void setFilled(boolean filled) { this.filled = filled; } public


java.util.Date getDateCreated( ) { return dateCreated; } public String
toString( )
{
return “created on “ + dateCreated
+ “\ncolor: “ + color + “ and filled: “ + filled;
}
} The Circle4 toString( ) method overrides the
GeometricObject1 toString( ) method ; it
invokes the GeometricObject1 toString( )
method and then modifies it to specify
public class Circle4 extends GeometricObject1 information specific to the circle4 object.

private double radius; public


Circle4( ) { }

public Circle4(double radius ) { this.radius = radius; } public


double getRadius( ) { return radius; }

public void setRadius( double radius) { this.radius = radius; }

public double getArea( ) { return radius * radius * Math.PI; } public double


getDiameter( ) { return 2 * radius; }

public double getPerimeter( ) { return 2 * radius * Math.PI; }

public void printCircle( )

System.out.println(“The circle is created “ + getDateCreated( ) + “ and the


radius is “ + radius);
}

public String toString( )


{
return super.toString( ) + “\nradius is “ + radius;
}

}
a. Rules for Overridding Inherited Methods

private data fields in a superclass are not accessible outside of that class, hence they
cannot be used directly by a subclass; they can be accessed &/or mutated by public
accessor &/or mutators defined in the superclass

an instance method can be overridden only if it is accessible; private methods cannot


be overridden

if a method defined in a subclass is private in its superclass, the two methods are
completely unrelated

a static method can be inherited, but a static method cannot be overridden remember that
static methods are class methods

if a static method defined in a superclass is redefined in a subclass, the method defined


in the superclass is hidden; the hidden static method can be invoked by using the syntax
“SuperClassName.staticMethodName( );”

b. Overriding versus Overloading

i. Overloading – same name, different signitures

ii. Overriding – method defined in the superclass, overridden in a subclass using


the same name, same signature, and same return type as defined in the
superclass

public class Test public class Test

{ {

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

{ {
a.p(10) invokes class A
A a = new A( ); a.p(10); A a = new A(a.p(10) invokes class B method;
); a.p(10);
method; hence prints 10
hence prints nothing
} }

} }
overloads
overrides
class B class B
{ {
public void p(int i){ } public void p(int i){ }

} }
4. Object Class & Methods

Every class in Java is descended from java.lang.Object

If no inheritance is declared when a class is defined, the class is a subclass of Object by


default

public String toString( );


returns a string consisting of the objects name, the @ sign, and the objects memory
address in hexadecimal, e.g., student@B7F9A1

o Override the toString( ) method to produce relevant information


concerning the subclass objects

o System.out.println(student);  System.out.println(student.toString( ));

public boolean equals(Object obj) { return (this == obj); }


default implementation tests whether two reference variables point to the same
object Invoked by the statement object1.equals(object2);

o Override the equals( ) method to test whether two distinct objects have
the same content, e.g.,
INSTANCEOF OPERATOR
public boolean equals(Object o)
{ o instanceof Circle
returns true if o is an instance of Circle
if (o instanceof Circle)
{
return radius == ((Circle)o).radius;
Do not use (Circle o) as the argument
} when overriding the equals( ) method,
i.e., do not use the signature
else return false; public boolean equals( Circle o)
} see page 355 #10.12

Comparison Operators/Methods
o “==” operator is used to compare primitive data type values
o “==” operator is also used to compare whether two reference variables
refer to the same object (where arrays may be considered to be objects)
o The modified “equals( )” method can be used to determine whether two
objects have the same contents

o The “equals( )” method can be modified to test the contents of all or a


selected subset of the data fields in the class
Inheritance can be defined as the procedure or mechanism of acquiring all the
properties and behavior of one class to another, i.e. acquiring the properties and
behavior of child class from the parent class. This concept was built in order to
achieve the advantage of creating a new class that gets built upon an already existing
class(es). It is mainly used for code reusability within a Java program. The class that
gets inherited taking the properties of another class is the subclass or derived class or
child class. Again, the class whose properties get inherited is the superclass or base
class or parent class. The keyword extends is used to inherit the properties of the
base class to derived class. The structure of using this keyword looks something
like this:

class base
{
.....
.....
}
class derive extends base
{
.....
.....
}
class Person {
void teach() {
System.out.println("Teaching subjects");
} }

class Person extends Teacher {


void listen() {
System.out.println("Listening to teacher");
} }

class CheckForInheritance {
public static void main(String args[]) {
Person s1 = new Students();
s1.teach();
s1.listen();
}
}

In this type of inheritance, a derived class gets created from another derived
class and can have any number of levels.

class Teacher {
void teach() {
System.out.println("Teaching subject");
}
}
class Student extends Teacher {
void listen() {
System.out.println("Listening");
}
}
class homeTution extends Student
{ void explains() {
System.out.println("Does
homework");
}
}
class CheckForInheritance {
public static void main(String argu[])
{ homeTution h = new
himeTution(); h.explains();
d.teach();
d.listen();
}
}

In this type of inheritance, there are more than 1 derived classes which
get created from one single base class.

class
Teacher {
void teach()
{
System.out.println("Teaching subject");
}
}

class Student extends Teacher


{ void listen() {
System.out.println("Listening");
}
}
class Principal extends Teacher
{ void evaluate() {
System.out.println("Evaluating");
}
}
class CheckForInheritance {
public static void main(String argu[])
{ Principal p = new Principal();
p.evaluate();
p.teach();
// p.listen(); will produce an error
}
}

Let us imagine a situation where there are three classes: A, B and C. The
C class inherits A and B classes. In case, class A and class B have a method
with same name and type and as a programmer, you have to call
that

method from child class's (C) object, there-there will be ambiguity as which method will be

called either of A or of B class.

So Java reduces this hectic situation by the use of interfaces which


implements this concept and reduce this problem; as compile-time errors
are tolerable than runtime faults in the program.
Polymorphism

The word polymorphism means having multiple forms. The term


Polymorphism gets derived from the Greek word where poly + morphos
where poly means many and morphos means forms.

Polymorphism is another special feature of object-oriented programming


(OOPs). The approach which lies beneath this concept is "single interface
with multiple implementations." This offers a single interface for controlling
access to a general class of actions.

a class defines a type


a type defined by a subclass is a subtype
a type defined by a superclass is a supertype

a variable must be declared to be of a specific type the type


of a variable called it’s declared type
a variable of a reference type can hold a null value or a reference to an object

an object is an instance of a class


a subclass is a specialization of its superclass

every instance of a subclass is an instance of its superclass


o every circle is an object

an instance of a superclass is not an instance of a subclass


o not every object is a circle

an instance of a subclass can be passed to a parameter of its superclass, i.e., a Circle


object can be passed to a GeometricObject class prarameter

polymorphism – an object of a subtype can be used whenever its superclass object


is required; i.e., a variable of a supertype can refer to a subtype object

dynamic binding – given an inheritance chain as follows,


class C4 class C3 class C2 class C1

and the object C1 o = new C1( );

if the object o were to invoke a method, i.e., o.p( ); then the JVM searches for the
method p( ) in the classes in the order C1, C2, C3, C4, java.lang.Object

once an implementation of p( ) is found, the search stops and that implementation


of p( ) is invoked
public class PolymorphismDemo
{
public static void main(String[ ] args)
{
m(new GraduateStudent( ));
m(new Student( ));
m(new Person( ));
m(new Object( ));
}

public static void m(Object x)


{

System.out.println(x.toString( ));
}
}

class GraduateStudent extends Student { }


class Student extends Person { public String toString( ) { return “Student”; } class
Person extends Object { public String toString( ) { return “Person”; }

The call for the execution of the method m(new GraduateStudent( ));

results in a the invocation of the toString( ) method; the JVM starts a search of the inheritance chain
starting with the GraduateStudent class for an implementation of the toString( ) method.

The Student class yields such an implementation which results in the output of the string “Student”.

The call for the execution of the method m(new Student( )); results in the invocation of its
toString( ) method and the output of the second string “Student”.

The call for the execution of the method m(new Person( )); results in the invocation of its
toString( ) method and the output of the string “Person”.

The call for the execution of the method m(new Object( )); results in the invocation of the
java.lang.Object’s toString( ) method and the output of a string similar to
“java.lang.object@AD23F5”.

A reference variable’s declared type determines which method is matched at compile time;
i.e., the compiler uses the parameter type, the number & order of parameters to determine
the matching method.
For a method defined in several subclasses, the JVM dynamically binds the
implementation of a method at runtime decided by the actual class of the object
referenced by the variable.
Recall that polymorphism refers to the use a variable of a supertype to refer to an object
of a subtype; the implementation is known as generic programming.
If a methods parameter type is a superclass, then an object of any of the subclasses
may be passed to the method via that parameter type.

5. Casting Objects & the instanceof Operator

a. Implicit Casting
Object o = new Student( ); m(
o ); equivalent m( new Student( ));
statements
An instance of Student is automatically an instance of Object

b. Explicit Casting
Student b = o;  compilation error !
An instance of Object is not necessarily an instance of Student

Student b = (Student) o;

c. Up Casting
Casting an instance of a subclass to a variable of a superclass is always possible; implicit
casting may be used.

d. Down Casting
Casting an instance of a superclass to a variable of a subclass: must use explicit
casting & object cast must be an instance of the subclass

error message ClassCastException

e. instanceof Operator
Object o = new Circle( );
if( o instanceof Circle )

double d = ((Circle) o ).getDiameter( ));

}
The declared type determines which method to match at compile time;

“o.getDiameter( );” would cause a compile error since Object does not contain a
“getDiameter( )” method.

To enable Generic Programming, declare variables with their


supertype; thus they can accept a value of any type.
f. TestPolymorphismCasting.java

public class TestPolymorphismCasting


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

Object o1 = new Circle4( 1 ); Object o2 =


new Rectangle1(1, 1); displayObject(o1);
displayObject(o2);
}
public static void displayObject(Object o)
{
if (o instanceof Circle4) Generic
{ Programming

System.out.println(((Circle4) o ).getArea( )); System.out.println(((Circle4) o


).getDiameter( ));
}
else if (o instanceof Rectangle1) System.out.println(((Rectangle1) o
).getArea( ));
}
}

Polymorphism can be achieved in two of the following ways:

 Method Overloading(Compile time Polymorphism)


 Method Overriding(Run time Polymorphism)

 Static Polymorphism is in other words termed as compile-time binding or


early binding.
 Static binding occurs at compile time. Method overloading is a case of
static binding and in this case binding of method call to its definition
happens at the time of compilation.

 To call an overloaded method in Java, it is must use the type and/or the
number of arguments to determine which version of the overloaded
method to actually call.
 The overloaded methods may have varied return types and the return
type single-handedly is insufficient to make out two versions of a
method.
 As and when Java compiler encounters a call to an overloaded method,
it simply executes the version of the method whose parameters match
the arguments used in the call.
 It permits the user to obtain compile time polymorphism with name
method name.
 An overloaded method is able to throw different kinds of exceptions.
 A method which is overloaded can contain different access modifiers.
Overloading method's argument lists might differ in:

 Number of parameters passed


 Data type of actual parameters
 Sequence of data type of actual parameters

class Mltply {

void mul(int a, int b) {


System.out.println("Sum of two=" + (a * b));
}

void mul(int a, int b, int c) {


System.out.println("Sum of three=" + (a * b * c));
}
}
class Polymorphism {
public static void main(String args[]) {
Mltply m = new Mltply();
m.mul(6, 10);
m.mul(10, 6, 5);
} }

Rules to method overriding

 Argument list: The argument list at the time of overriding method need
to be same as that of the method of the parent class. The data types of
the arguments along with their sequence must have to be preserved as it
is in the overriding method.
 Access Modifier: The Access Modifier present in the overriding method
(method of subclass) cannot be more restrictive than that of an
overridden method of the parent class.
 The private, static and final methods can't be overridden as they are
local to the class.
 Any method which is overriding is able to throw any unchecked
exceptions, in spite of whether the overridden method usually method
of parent class might throw an exception or not.

//method overriding
class parent {
public void work() {
System.out.println("Parent is under retirement from work.");
}
}
class child extends parent {
public void work() {
System.out.println("Child has a job");
System.out.println(" He is doing it well");
}
public static void main(String argu[]) {
child c1 = new child();
c1.work();
} }

Advantage of method overriding

One major advantage of method overriding is that a class can give its own specific
execution to an inherited method without having the modification in the parent
class (base class).

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. }}
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.

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}

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 simple example:

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

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. }}

Method Overloading in Java

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

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. }}

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. }}

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 subclass provides the specific implementation of the method


that has been provided by one of its 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

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).
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike2 obj = new Bike2();
9. obj.run();
10. }

ABSTRACTION

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing


only functionality to the user.

Another way, it shows only important things to the user and hides the internal
details for example sending sms, you just 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 that is declared as abstract is known as abstract class. It needs to


be extended and its method implemented. It cannot be instantiated.

Example abstract class

1. abstract class A{ }

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

Example abstract method

1. abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method

In this example, Bike the abstract class that contains only one abstract
method run. It implementation is provided by the Honda class.

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely..");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown
by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In real scenario, object is provided thro
ugh method e.g. getShape() method
15. s.draw();
16. }
17. }
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.

Java Interface also represents IS-A relationship. It

cannot be instantiated just like abstract class. Why

use Java interface?

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

 It is used to achieve abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling

Java Interface Example

In this example, Printable interface has only one method, its implementation
is provided in the A class.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }

Differences between abstract class and interface that are given below.

Abstract class Interface


1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods. Since Java 8, it can have default and static
methods also.
2) Abstract class doesn't support
Interface supports multiple inheritance.
multiple inheritance.
3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables.
variables.
4) Abstract class can provide the Interface can't provide the
implementation of interface. implementation of abstract class.
5) The abstract keyword is used The interface keyword is used to declare
to declare abstract class. interface.
6)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

1. interface A{
2. void a(); void b();
3. void c(); void d();
4. }
5. abstract class B implements A{
6. public void c(){System.out.println("I am c");}
7. }
8. class M extends B{
9. public void a(){System.out.println("I am a");}
10. public void b(){System.out.println("I am b");}
11. public void d(){System.out.println("I am d");}
12. }
13. class Test5{
14. public static void main(String args[]){
15. A a=new M();
16. a.a();
17. a.b();
18. a.c();
19. a.d();
20. }}

You might also like