Abstract Class in Java
In C++, if a class has at least one pure virtual function, then the
class becomes abstract. Unlike C++, in Java, a separate keyword abstract
is used to make a class abstract.
An example abstract class in Java
abstract class Shape {
int color;
// An abstract function (like a pure virtual function in C++)
abstract void draw();
}
Following are some important observations about abstract classes in Java.
1) Like C++, in Java, an instance of an abstract class cannot be created, we can have references of abstract class type though.
2) Like C++, an abstract class can contain constructors in
Java. And a constructor of abstract class is called when an instance of
a inherited class is created. For example, the following is a valid
Java program.
3) 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.
4) Abstract classes can also have final methods (methods
that cannot be overridden). For example, the following program compiles
and runs fine.
Comments
Post a Comment