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

Abstract Class

Uploaded by

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

Abstract Class

Uploaded by

Bhavish Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Abstract Class and Methods

in Java
Dr Richa
Assistant Professor
Abstract Means

• Abstract means a small description that gives you an imaginative idea


about the concept.
• Classes are divided into two: concrete class and abstract class
• Abstract Classes in Java simply declare the methods that are needed to
be implemented by the class which extends the abstract class.
• The abstract class hides the internal details of method implementation
showing only essential information to the user - the method name.
• Class can be abstract without any abstract method also. It may have zero
or more abstract method
Abstract Class
• An Abstract Class is nothing but a blueprint for the child
class. Abstract classes justify the layout of your idea and do not really
implement them.
Abstract Class
• An abstract class is a class that cannot be instantiated and is primarily meant to be
subclassed by other classes.
• A class that is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods. An abstract method is a method that is
declared without any implementation. If an abstract class is inherited to derived class
then derived class will also become abstract unless it override the abstract method.
• Syntax
abstract class class_name
{
//abstract and non abstract methods
}
Why Abstract Class in Java
Template Programming
• Abstract classes provide a blueprint to be followed by the classes that
extend the Abstract class. Abstract Class because it gives a predefined
template for any future specific class that you might need.
Code Reusability
• Using an abstract class in an application saves time. We can declare an
abstract method in the abstract class and call it from anywhere
required. Abstract classes eliminate the need to repeatedly write the
same code.
Why Abstract Class in Java
Abstraction
• Data abstraction in Java helps the developers hide the actual method
implementation from the end user and display only the method names (APIs).
Abstract classes in Java help implement the concept of Abstraction as discussed
before.
Dynamic Method Resolution
• Last but not least is Dynamic Method Resolution. The Abstract Classes enable
us with dynamic method resolution or the dynamic method dispatch process. The
dynamic Method Resolution is a procedure where, at runtime, the calling of an
overridden method is resolved.
• This is how RunTime polymorphism is implemented. Whenever any method
which is overridden is called by reference, it is JVM's responsibility to check the
version of the method to execute depending upon the type of object.
Rules for using Abstract Class in Java
• You have to use the keyword abstract.
• You cannot instantiate an abstract class.
• An abstract class can contain both abstract and non-abstract methods.
• You can include non-abstract final methods (a method that cannot be
overridden) as well in your abstract class.
• Final methods in abstract classes can not be abstract. They must be
implemented in the abstract class itself.
• You can also include constructors and non-abstract static methods in
your abstract class.
Abstract Method in Java
• If you use the abstract keyword while declaring the method, it is
called an Abstract Method.
• An Abstract Method does not contain anybody. Whenever you declare
an abstract method, you must end it with a semicolon
• An abstract method is always present inside an abstract class, you
cannot declare it inside the regular (not abstract) class.
Syntax
abstract class Base
{
abstract void display();
}
class derived extends Base
{
//override abstract method of base class
}
General Example
class Base { public class Main{
public Base(){ public static void main(String[] args)
{
System.out.println("super base class");
Base b=new Derived();
}
public void method1() { b.method1();
System.out.println("Method1 super base class");
b.method2();
}
}
public void method2(); }
}
class Derived extends Base{ Output:
error: missing method body, or declare abstract
public void method2() {
Adding abstract in method2 will not be sufficient
System.out.println("Method2 super base class"); error: Base is not abstract and does not override abstract
} method method2() in Base

}
Example of Abstract class and Method
abstract class Base {
public Base() public class Main
{ {
System.out.println("super base class"); public static void main(String[] args)
{
}
public void method1() { Base b=new Derived();
System.out.println("Method1 super base class"); b.method1();
} b.method2();
}
abstract public void method2();
}
}
class Derived extends Base{
public void method2() { Output:
System.out.println("Method2 super base class"); super base class
Method1 super base class
}
Method2 super base class
}
How abstract class is useful
abstract class Hospital Class MyHospital extends Hospital
{
{ MyHospital()
{
abstract void emergency();
}
abstract void appointment(); void Emergency()
{
abstract void admit(); }
void appointment()
abstract void billing(); {
}
} ……
……
}
Explanation
• The abstract class only gives you the standard; the hospital class gives you
standard of an ideal hospital where emergency, appointment etc will be
there. Once you create your own hospital, say Fortis, where you follow all the
standard then only you will be able to create the instance of the hospital.
• We cannot create instance of abstract class: The body which gives the
standard they cannot show you the hospital, they only gives you guideline. If
fortis is opening there hospital then they will follow the standard and can
show you the hospital.
• But the abstract class can have the reference. If you have the reference then
you can create the object of concrete subclass. Since everyone will say that
fortis is hospital which has features as a standard hospital. That is why
reference of the hospital is allowed.
Another Example
Class MyKFC extends KFC
abstract class KFC {
MyKFC()
{
{
public KFC() ……
{ }
void billing()
} {
void makeFood() }
{ void offer()
{
…… }
} void
abstract void billing(); }

abstract void offer();


}
Explanation
• KFC is an abstract class which provide standard where it has one
constructor and one method that gives instruction that how food will
be made in KFC. Billing is upto the sub-class that how they want to do
billing, but billing method must be there in sub-class. Similarly, offer
must be there in sub class but when to give offer is upto the sub-class.
• Any franchise of KFC extends KFC class. They will show the franchise
that how they have made the food. And similar for the offer and
billing. Franchise can add more method in their own class.
Do’s and don’t of Abstract class
• We can not create object of abstract class
• If you have a class and method body is blank then you have to make the class abstract.
• If you have a class then you can not make it final: since final purpose is no more changes and abstract purpose
is inheritance
abstract final class Base {
public Base(){
System.out.println("super base class");
}
public void method1() {
System.out.println("Method1 super base class");
}
abstract public void method2();
}
Output: illegal combination of modifiers: abstract and final
Do’s and don’t of Abstract class
• Abstract methods cannot be made as final, it will give error as: illegal combination of
modifiers: abstract and final
• Abstract class can not be made as static
abstract static class Base
{
public Base(){
System.out.println("super base class");
}
public void method1() {
System.out.println("Method1 super base class");
}
abstract public void method2();
}
Output: modifier static not allowed here
Do’s and don’t of Abstract class
• Static means that it must have body and we can call it without an object
using class name
• In Java, just like in C++ an instance of an abstract class cannot be created, we
can have references to abstract class type though.
• Like C++, an abstract class can contain constructors in Java. And a constructor
of an abstract class is called when an instance of an inherited class is created.
• In Java, we can have an abstract class without any abstract method. This allows
us to create classes that cannot be instantiated but can only be inherited.
• Abstract classes can also have final methods (methods that cannot be
overridden)
• We can use the abstract keyword for declaring top-level classes
(Outer class) as well as inner classes as abstract
• If the Child class is unable to provide implementation to all abstract
methods of the Parent class then we should declare that Child class as
abstract so that the next level Child class should provide
implementation to the remaining abstract method.
Conclusion
• Points to remember are mentioned below:
• An abstract class is a class that can not be initiated by itself, it needs to be
subclassed by another class to use its properties.
• An abstract class can be created using “abstract” keywords.
• We can have an abstract class without any abstract method.
Interface
• An interface is a set of abstract methods you would want your class to
implement. These methods are public and abstract by default(you
don’t have to explicitly use the “abstract” keyword), and any class
implementing your interface will need to provide implementations of
those methods.
• Why Interface
Example
Interface Test
{
void method1();
void method2();
}
Class Test1 implements Test
{
public void method1()
{
}
public void method2()
{
}
}
Interface is abstract class with all abstract method and purpose is polymorphism.
Test t=new Test1();
A class can extend from only one class but a class can implement more than one interface
Example
interface Test
{
void method1();
void method2();
}
public class Main
{
public static void main(String[] args)
{
Test t=new Test();
}
}
Output: error: Test is abstract; cannot be instantiated
Note: if you will provide body to any method of interface then it will give you error error:
interface abstract methods cannot have body
Example
interface Test {
void method1();
void method2();
}
class Test1 extends Test
{

}
public class Main{
public static void main(String[] args) {
Test t=new Test();
}
}
Output: error: no interface expected here
error: Test is abstract; cannot be instantiated
Example Interface
interface Test {
void method1(); public class Main{
void method2(); public static void main(String[] args)
} {
class Test1 implements Test{ Test t=new Test1();
public void method1() { t.method1();
System.out.println("Method1 of class Test1"); t.method2();
} }
public void method2() {
}
Output:
System.out.println("Method2 of class Test1");
Method1 of class Test1
}
Method2 of class Test1
public void method3() {
System.out.println("Method3 of class Test1");
}
}
What would be the output?
interface Test {
void method1(); public class Main{
void method2(); public static void main(String[] args)
} {
class Test1 implements Test{ Test t=new Test1();
public void method1() { t.method1();
System.out.println("Method1 of class Test1"); t.method2();
} t.method3();
public void method2() {
}
}
System.out.println("Method2 of class Test1");
Output:
}
error: cannot find symbol
public void method3() { Example of Dynamic Method Dispatch or
System.out.println("Method3 of class Test1"); Runtime Polymorphism
}
}
To call Method3 Create reference of Test1
interface Test {
void method1(); public class Main{
void method2(); public static void main(String[] args)
} {
class Test1 implements Test{ Test1 t=new Test1();
public void method1() { t.method1();
System.out.println("Method1 of class Test1"); t.method2();
} t.method3();
public void method2() {
}
}
System.out.println("Method2 of class Test1");
Output:
}
Method1 of class Test1
public void method3() { Method2 of class Test1
System.out.println("Method3 of class Test1"); Method3 of class Test1
}
}
Example of Interface in Java Class
{
Phone

void call()
Class smartphone extends phone implement camera, musicPlayer {
{ }
void videocall() void sms()
{
{
}
}
}
void click() Interface Camera
{ {
} void click();
void record() void record();
{ }
} Interface MusicPlayer()
void play(){…} {
void pause(){…} void play();
Smartphone S=new Smartphone(); void pause();
void stop(){…}
Phone P=S; void stop();
}
Camera C=S; }
MusicPlayer M=S;
class SmartPhone extends Phone implements Camera, MusicPlayer{
public void record() {
System.out.println("video call");
}
public void click() {
System.out.println("video call");
}
class Phone { public void play() {
public void call() { System.out.println("play");
}
System.out.println("call");
public void stop() {
} System.out.println("stop");
public void msg() { }
System.out.println("Msg"); }
public class Main{
} public static void main(String[] args) {
} SmartPhone S=new SmartPhone();
interface Camera{ Phone P=S;
Camera C=S;
void click(); MusicPlayer M=S;
void record(); P.call();
} P.msg();
C.click();
interface MusicPlayer{ C.record();
void play(); M.play();
void stop(); M.stop();
}
} }
Interface
• Class phone is concrete class, and its method can be there. Interface
is camera and musicPlayer.
• Camera can be class also, in some situation can be interface also.
• Object is created for smartphone. Using object, I can call all methods
of smartphone.
• We can have a phone reference where object of smartphone can be copied.
So basically, I want to say that I can use the smartphone as phone also. That
means I can only call those methods that is of phone and not of smartphone.
• Similarly, I can have a camera reference which is copying the smartphone
object, and it can only call the methods of camera
• The same applies on the reference of the music Player.
• In the previous example while using the reference of phone, camera
and music player can be used by the object of smartphone but only
can be used as phone, camera and music player. It cannot access the
smartphone methods.
• Since the class smartphone is implementing two interface; one is
camera, and another is music player. And that is why we can create an
object of smartphone that can be referenced through phone, camera
and music player.
To Declare and use in Interface in Java
interface Car
{
public void start();
}
• Methods declared inside an interface are implicitly marked as public
and abstract, and variables declared inside an interface are implicitly
marked as public static final by the compiler.
• Why are member variables in an interface implicitly made public,
static, and final?
• To use an interface in Java, a class must implement it using
the implements keyword and override (provide its own
implementations) all the methods declared in the interface.
Example
interface Car {
public void start();
}
class Mechanic implements Car {
public void start() {
System.out.println("Mechanic class");
}
}
public class Main{
public static void main(String[] args) {
Mechanic m=new Mechanic();
m.start();
}
}
• What would happen if a class does not provide implementations of all
the methods declared in an interface it is implementing?
Why Interface
• Better polymorphism: With interfaces, you don’t have to make everything fit into one
family of classes, offering much more flexibility.
• Multiple inheritances: In Java, we cannot extend multiple classes because of the
famous Diamond problem (explained later in this article). To solve this, we can use a
Java interface to give child classes the freedom to extend whatever parent class they
wish (and implement our interface) rather than forcing them to extend a specific base
class to use our functionality.
• For abstraction: Interfaces help to achieve security, hide certain details, and only
show the relevant and necessary information. For example, when we start our car, we
just plug in the key and start the car without worrying about the nitty-gritty details of
what happens underneath when the car starts. This is a great example of abstraction!
We carry out our task, that is, starting the car, but we don’t need to take care of
anything else that happens in the background when starting the car.
• The method in the interface can not be private; since its to be
implemented by other classes. The methods are by default public.
Also, its by default abstract.
• If you want to give any variable in interface then it should be in
uppercase and these identifier are by default static and final, that
means it’s a constant.
• You can not give body to method of the class otherwise it will give
error. But if the method is static in the interface then it will work. So
the interface can have method with body that is static
Example
interface Test {
int X=10;
public void method1();
public static void method2()
{
System.out.println("In method 2");
}
}
public class Main{
public static void main(String[] args) {
System.out.println(Test.X);
Test.method2();
}
}
Output:
10
In method 2
Note: If you want to implement Test through some class. Creating the object of class will cause compilation error since
Guess the output
System.out.println(t2.X);
interface Test {
System.out.println(Test.X);
int X=10; t2.show();
void show();
} }
class Test2 implements Test }
{ Output:
public void show2() 10
10
{
In test show10

System.out.println("In test show"+Test.X);


}
}
public class Main{
public static void main(String[] args)
{
Test2 t2=new Test2();
Guess the output
System.out.println(t2.X);
interface Test {
System.out.println(Test.X);
int X=10; t2.show();
void show();
} }
class Test2 implements Test }
{ Output:
public void show2() error: cannot assign a value to final variable X
{
Test.X=20;
System.out.println("In test show"+Test.X);
}
}
public class Main{
public static void main(String[] args)
{
Test2 t2=new Test2();
• An interface can extend another interface
• Java8 onwards default methods are also allowed inside the interface
so you can change the static method to default. So while extending
the interface the class can override the abstract method. But it
depends on the requirement that whether or not the default method
will be override.
• private can also be the access modifier of the interface method but it
can not be inherited but it can be used inside the interface. And also
may be used by default method of the class.
Example
interface Test {
public void method3(){
int X=10;
System.out.println("method 3 in mytest");
public void method1(); }
default void method2() { }
System.out.println("In method 2"); public class Main{
} public static void main(String[] args) {
} MyTest my=new MyTest();
my.method1();
interface Test1 extends Test{
my.method3();
public void method3(); my.method2();
} }
class MyTest implements Test, Test1{ }
public void method1(){ Output:
System.out.println("method 1 in mytest"); Method1 in mytest
Method3 in mytest
}
In method2
Multiple Inheritance vs Interface
• The way C++ and java observes Mutiple Inheritance is different. In C++
• Smartphone is a Phone
• Smartphone is a Camera
• Smartphone is a MusicPlayer
• In case of java
• Smartphone is a Phone
• Smartphone has a Camera
• Smartphone has a MusicPlayer
• Suzuki is a car that has MusicPlayer whereas in C++ Suzuki is a car.
The diamond Problem
• Car is a super class that has a method start()
• DieselCar is a class that inherit the class Car. Now DieselCar also has
method start()
• Sedan is a class that inherit the class Car. It also has method start()
• Another class Honda that inherit both DieselCar and Sedan and now
the problem is start() is coming from whom?
• This problem can be resolved as Sedan can be made as interface
• At the same time if an interface has same body of default method
than the other interface then the class that implements both of the
interface must override the common method otherwise it will
generate compile time error. Also, the overridden method will be
called by the object of the class.
Example
interface Test {
default void show() { public class Main
System.out.println("In test show"); {
public static void main(String[] args)
} {
} Test2 t2=new Test2();
interface Test1 { t2.show();
default void show() { }
}
System.out.println("In test1 show"); Output:
} In test1 show
}
class Test2 implements Test, Test1
{
public void show() {
System.out.println("In test1 show");
}
}
What would be the output
interface Test { public class Main
{
default void show() { public static void main(String[] args)
System.out.println("In test show"); {
} Test2 t2=new Test2();
} t2.show();
Test t1=new Test2();
interface Test1 {
t1.show();
default void show() { }
System.out.println("In test1 show"); }
} Output:
} In test2 show
In test2 show
class Test2 implements Test, Test1 {
public void show() {
System.out.println("In test2 show");
}
}
What would be the output
interface Test {
default void show() { public class Main
System.out.println("In test show"); {
public static void main(String[] args)
} {
} Test2 t2=new Test2();
interface Test1 { t2.show();
}
default void show() {
}
System.out.println("In test1 show");
} Output:
} In test show
In test1 show
class Test2 implements Test, Test1 {
In test2 show
public void show() { Note: Writing only Test.show() will generate error
Test.super.show(); error: non-static method show() cannot be
Test1.super.show(); referenced from a static context
System.out.println("In test2 show");
}
}
If only interface methods needs to be
executed public void showTest()
{
interface Test { Test.super.show();
default void show() { }
System.out.println("In test show"); public void showTest1()
} {
} Test1.super.show();
interface Test1 { }
}
default void show() {
public class Main{
System.out.println("In test1 show");
public static void main(String[] args)
} {
} Test2 t2=new Test2();
class Test2 implements Test, Test1 { t2.showTest();
public void show() { t2.showTest1();
Test.super.show(); }
Test1.super.show(); }
Output:
System.out.println("In test2 show");
In test show
}
In test1 show
Is there is no common method then direct class
object is sufficient to call method of interface
interface Test {
default void show() { public class Main
{
System.out.println("In test show");
public static void main(String[] args)
} {
} Test2 t2=new Test2();
interface Test1 { t2.show();
default void show1() { t2.show1();
t2.show2();
System.out.println("In test1 show"); }
} }
} In case outer and inner class
class Test2 implements Test, Test1 { Derived1 outer=new Derived1();
Derived1.Derived2 inner=outer.new Derived1();
public void show2() {
Inner.innerMedthod();
System.out.println("In test2 show");
}
}
Difference between Abstract class and Interface
Sr. No. Key Abstract Class Interface

Interface can have only abstract methods. Java 8


Abstract class can have both an abstract as well
1 Supported Methods onwards, it can have default as well as static
as concrete methods.
methods.

2 Multiple Inheritance Multiple Inheritance is not supported. Interface supports Multiple Inheritance.

final, non-final, static and non-static variables


3 Supported Variables Only static and final variables are permitted.
supported.

Interface can not implement an interface, it can


4 Implementation Abstract class can implement an interface.
extend an interface.

5 Keyword Abstract class declared using abstract keyword. Interface is declared using interface keyword.

Abstract class can inherit another class using


6 Inheritance Interface can inherit only an inteface.
extends keyword and implement an interface.

Abstract class can be inherited using extends Interface can only be implemented using
7 Inheritance
keyword. implements keyword.

Abstract class can have any type of members like


8 Access
private, public. Interface can only have public members.

You might also like