This article introduces abstract classes and abstract methods in Java, with the keyword abstract representing abstraction, which is a keyword that can be used to modify classes and methods. If the class name is preceded by an abstract modification, this class is an abstract class. If the method name is preceded by an abstract modification, this method is an abstract method. Why should have abstract class, abstract class is mainly used to write interface, interface in the next introduction. You simply need to define a class in an abstract, without a specific implementation. The subclass can then inherit this abstract class, and subclasses will implement abstract methods in the abstract class, respectively. The method inside the abstract class is not necessarily an abstract method, but a class with abstract methods must be an abstract class. Abstract methods in abstract classes do not need to be implemented specifically, they should be implemented by subclasses.
Abstract classes and abstract methods have the following characteristics
1) An abstract class cannot initialize an instance object of a class, but can create a reference to a subclass.
2) Abstract methods do not need to implement, only need to declare, let subclasses to implement
Let's take a look at the first feature
We define a parent class that is an abstract class.
Package Lesson01;
Abstract public class Student {
public int getage () {
return 0;
}
}
Define a subclass that inherits this student class
Package Lesson01;
public class Student_abc extends Student {
public int getage () {
return 15;
}
}
Test the class and run it:
Package Lesson01;
public class MyClass {
public static void Main (string[] args) {
Student st_abc = new Student_abc (); (running correctly, abstract classes cannot create instances, but can create references to subclasses)
System.out.println (St_abc.getage ());
Student st = new Student (); (Will error, because abstract classes cannot create instances)
}
}
2. Abstract methods do not need to be implemented, so that subclasses can implement them.
This time, we changed the parent class to the following
Package Lesson01;
Abstract public class Student {
Abstract public int getage ();
}
Here, if you have to write the implementation method in Getage (), this place will error.
Subclass inherits Parent class, implements Getage () method
Package Lesson01;
public class Student_abc extends Student {
public int getage () {
return 15;
}
}
Test class:
Package Lesson01;
public class MyClass {
public static void Main (string[] args) {
Student st_abc = new Student_abc ();
System.out.println (St_abc.getage ());
}
}
Test Pass
Java Foundation 13: Abstract Classes and methods