Page 219 - PowerPoint Presentation
P. 219
CAVITE STATE UNIVERSITY
T3 CAMPUS
Department of Information Technology COSC 65 – Programming Languages
public class TestAbstraction2 {
public static void main(String[]args) {
Shape shape = new Circle(); // in real scenario, object is provided through method
shape.draw();
} }
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.
abstract class Bike {
Bike() {
System.out.println(“bike is created”);
}
abstract void run(); // this is the abstract method
void changeGear() {
System.out.println(“gear changed”);
}
}
class Honda extends Bike { // creating a Child class which inherits Abstract class
void run() { // this is not an abstract method
System.out.println(“running safely”);
}
}
public class TestAbstraction3 { // creating a Test class which calls abstract and non
abstract methods
public static void main(String[]args) {
Bike Bike = new Honda();
Bike.run();
Bike.changeGear();
} RULE: if there is an abstract method in a class,
} that class must be abstract.
A Java abstract class is a class which cannot be instantiated, meaning you cannot
create new instances of an abstract class. The purpose of an abstract class is to function as
a base for subclasses. For example, there are situations in which you will want to define a
superclass that declares the structure of a given abstraction without providing a complete
implementation of every method. That is, sometimes you will want to create a method. That
is, sometimes you will want to create a superclass that only defines a generalized form that
will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a
class determines the nature of the methods that the subclasses must implement.
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.
Page | 78