Абстрактные классы в 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.
Java
// An example abstract class in Java abstract class Shape { int color; // An abstract function (like a pure virtual function in // C++) abstract void draw(); } |
Ниже приведены некоторые важные наблюдения об абстрактных классах в Java.
1) Like C++, in Java, an instance of an abstract class cannot be created, we can have references to abstract class type though.
Java
abstract class Base { abstract void fun(); } class Derived extends Base { void fun() { System.out.println( "Derived fun() called" ); } } class Main { public static void main(String args[]) { // Uncommenting the following line will cause // compiler error as the line tries to create an // instance of abstract class. Base b = new Base(); // We can have references of Base type. Base b = new Derived(); b.fun(); } } |
Derived fun() called
2) Как и C ++, абстрактный класс может содержать конструкторы в Java. А конструктор абстрактного класса вызывается при создании экземпляра унаследованного класса. Например, ниже представлена действующая программа на Java.
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.
Java
// An abstract class without any abstract method abstract class Base { void fun() { System.out.println( "Base fun() called" ); } } class Derived extends Base { } class Main { public static void main(String args[]) { Derived d = new Derived(); d.fun(); } } |
Base fun() called
4) Abstract classes can also have final methods (methods that cannot be overridden). For example, the following program compiles and runs fine.
Java
// An abstract class with a final method abstract class Base { final void fun() { System.out.println( "Derived fun() called" ); } } class Derived extends Base { } class Main { public static void main(String args[]) { Base b = new Derived(); b.fun(); } } |
Derived fun() called
5) For any abstract java class we are not allowed to create an object i.e., for abstract class instantiation is not possible.
Java
// An abstract class example abstract class Test { public static void main(String args[]) { // Try to create an object Test t = new Test(); } } |
Выход:
Ошибка времени компиляции. Тест абстрактный; не может быть создан Test t = new Test ();
6) Similar to the interface we can define static methods in an abstract class that can be called independently without an object.
Java
abstract class Party { static void doParty() { System.out.println( "Lets have some fun!!" ); } } public class Main extends Party { public static void main(String[] args) { Party.doParty(); } } |
Lets have some fun!!
Упражнение:
1. Можно ли создать в Java абстрактный и конечный класс?
2. Возможно ли иметь абстрактный метод в итоговом классе?
3. Возможно ли наследование от нескольких абстрактных классов в Java?
Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.
Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .