Java-抽象类
时间:2020-02-23 14:36:20 来源:igfitidea点击:
在本教程中,我们将学习Java编程语言中的抽象类。
在以前的教程中,我们了解了继承和方法重写。
随时检查一下。
因此,使用方法重写子类或者子类将通过创建与父类中的方法具有相同名称的方法来覆盖超类或者父类的方法。
抽象化
抽象是父类或者超类具有未实现的方法的概念。
也就是说,没有身体的方法。
并且期望继承父类的子类或者子类将实现该方法。
我们使用"抽象"关键字标记一个抽象类。
子类需要实现的方法也被标记为"抽象"。
语法
abstract class MyClass {
abstract type myMethod(param_list);
//some code goes here...
}
其中," MyClass"是抽象类的名称,因为它由" abstract"关键字标记。
预期由子类实现的名为" myMethod"的方法被标记为"抽象"。
抽象方法的返回类型由type表示,而'param_list'表示抽象方法将具有的参数列表。
注意点!
以下是使用抽象时要注意的几点。
抽象类必须在关键字" class"之前具有" abstract"关键字。
子类将要实现的方法必须用
abstract关键字标记。如果继承抽象类的子类未实现"抽象"方法,则子类也必须标记为"抽象"类。
抽象类也可以具有完全实现的方法和其他成员变量。
我们无法实例化抽象类的对象。
例1:继承一个抽象类
在下面的示例中,我们有一个抽象类MyMessage和一个抽象方法greetings。
该类由" HelloWorld"类继承,并且其中实现了抽象方法" greetings"。
//abstract class
abstract class MyMessage {
//member variable
String message;
//abstract method that needs
//to be implemented by child class
abstract void greetings();
//fully implemented method
public void awesome() {
System.out.println("Awesome!");
}
}
//class inheriting the abstract class
class HelloWorld extends MyMessage {
//constructor
HelloWorld(String message) {
//note!
//this message is inherited from
//the parent class MyMessage
this.message = message;
}
//implementing the abstract method
//of the parent class
void greetings() {
System.out.println("Hello World");
}
public void showMessage() {
System.out.println("Message: " + this.message);
}
}
//main class
public class Example {
public static void main(String[] args) {
//instantiate an object
HelloWorld obj = new HelloWorld("My name is .");
//method call
obj.greetings();
obj.awesome();
obj.showMessage();
}
}
$javac Example.java $java Example Hello World Awesome! Message: My name is .
示例2:多级继承
在下面的示例中,我们有具有抽象方法greetings的Happy类。
"快乐"类是由"真棒"类继承的,但此处未实现抽象方法。
因此,我们将" Awesome"类标记为" abstract"。
然后,我们有一个" HelloWorld"类,该类继承了" Awesome"类并实现了抽象的" greetings"方法。
//abstract class
abstract class Happy {
//abstract method that needs
//to be implemented by child class
abstract void greetings();
}
//inheriting the abstract class
//but not implementing the abstract method
//so, this class is marked as abstract
abstract class Awesome extends Happy {
//abstract method that was inherited from
//the parent class Happy but not
//implemented in this class
//so marked as abstract method
abstract void greetings();
}
//this class implements the abstract method
class HelloWorld extends Awesome {
//implementing the inherited
//abstract method
void greetings() {
System.out.println("Hello World");
}
}
//main class
public class Example {
public static void main(String[] args) {
//instantiate an object
HelloWorld obj = new HelloWorld();
//method call
obj.greetings();
}
}
$javac Example.java $java Example Hello World

