ABSTRACT CLASS Abstract Class Sometimes a superclass is
ABSTRACT CLASS
Abstract Class • Sometimes a super-class is aimed only at acting as a “common model” for the sub-classes, and no reason exists to actually instantiate it. • In this case, it may be declared as “abstract. ” public abstract class Shape {. . . } • Abstract classes CANNOT be instantiated. 2
Abstract Class • You create an abstract class when you want to manipulate a set of classes through this common interface. • Abstract classes can contain whatever an “ordinary” class can: instance and class variables, instance and class methods, with whatever modifiers. • Moreover, abstract classes can contain abstract methods. 3
Abstract Method • An abstract method is given the signature only. • An abstract method is not equipped with a body, i. e. no implementation is given for it. • The implementation of the body of an abstract method is provided in sub-classes of the abstract class. 4
Abstract Method • A method can be declared abstract if and only if it is contained in an abstract class. • Abstract methods “roughly” describe within a super-class behaviors that are exhibited by subclasses. • Each subclass is in charge of providing the correct specific implementation for such behaviors. 5
Example public abstract class Shape { protected double x, y; public void display() { System. out. println(“Coordina te: “+x+”, ”+y); } public abstract double area(); } Sub-classes of Shape inherit the concrete method display() and variables x and y They MUST implement the method area() as well 6
Implementation of Abstract Method class Circle extends Shape { protected double radius; public Circle(double r){ radius=r; } public double area() { return(radius*3. 1415} ; } } class Square extends Shape{ protected double edge; public Square(double e){ edge=l; } public double area() { return(edge*edge); } } 7
Implement the Concept public class Test. Abstract. Class{ public static void main(String[] args){ Shape 1 obj 1 = new Square(3. 1); obj 1. display(); System. out. println("n. Area of Square: "+obj 1. area()); Shape 1 obj 2 = new Circle(4. 5); obj 1. display(); System. out. println("n. Area of Circle: "+obj 2. area()); Square obj 3 = new Square(5. 0); obj 3. display(); System. out. println("n. Area of Square: "+obj 3. area()); // Shape 1 obj 4 = new Shape 1(); } } 8
Object Creation • Alternatives; – Shape 1 obj 1 = new Square(3. 1); – Square obj 3 = new Square(5. 0); • NOT ALLOWED; – Shape 1 obj 4 = new Shape 1(); 9
Demo Session • Let us convince ourselves regarding abstract class concept by running the previous codes in the Textpad. 10
Summary • Before we end the session, let us remind ourselves on the following points; – Abstract class must contain at least one abstract method. – Object cannot be created from abstract class. – Subclass must implement the abstract method, otherwise it will also become abstract. – Abstract method contains only a signature. 11
END OF ABSTRACT CLASS
13
- Slides: 13