This document discusses abstract classes in Java. It defines an abstract class as a class declared with the abstract keyword that may contain abstract and non-abstract methods. Abstract classes cannot be instantiated and require subclasses to implement any abstract methods. The document provides examples of abstract class and method declarations and demonstrates how subclasses must implement abstract methods to be instantiated. It also outlines some key uses of abstract classes such as code sharing among related classes.
2. INTRODUCTION
? ¡°Abstraction¡± is a process of hiding the implementation
details and showing only functionality to the user.
? It shows only essential things to the user and hides the
internal details.
? There are two ways to achieve abstraction in java
1) Abstract class (0 to 100%)
2) Interface (100%)
3. ABSTRACT CLASS & METHOD
? An abstract class is a class that is declared ¡±abstract¡± it may or may
not include abstract methods.
? A method which is declared as ¡°abstract¡± and does not have
implementation is known as an abstract method.
? Syntax :
modifier abstract class className
{
abstract dataType methodName();
}
modifier class childClass extends className
{
dataType methodName(){}
}
4. ? An abstract class must be declared with an abstract keyword.
? It can have abstract and non-abstract methods.
? It cannot be instantiated.
? It can have constructors and static methods also.
? It can have final methods which will force the subclass not to
change the body of the method.
? Any class which contains an abstract method must also be abstract.
POINTS TO REMEMBER
6. abstract class Animal //Abstract Class Declaration
{
public abstract void sound(); //Abstract Method Declaration
}
public class Dog extends Animal //Dog inherits from Animal
{
public void sound()
{
System.out.println("Woof");
}
public static void main(String args[])
{
Animal obj = new Dog();
obj.sound();
}
}
OUTPUT : Woof
8. abstract class MyClass
{
public void disp()
{
System.out.println("Concrete method of parent class");
}
abstract public void disp2();
}
class Demo extends MyClass
{
public void disp2()
{
System.out.println("overriding abstract method");
}
public static void main(String args[])
{
Demo obj = new Demo();
obj.disp2();
}
}
OUTPUT : overriding abstract method
9. ? To share code among several closely related classes.
? If classes that extend your abstract class have many common
methods or fields or require access modifiers other than public
(such as protected and private).
? You want to declare non-static or non-final fields. This enables
you to define methods that can access and modify the state of
the object to which they belong.
USE OF ABSTRACT CLASS