Differences between abstract classes and interfaces
1. When abstract is used to modify a class, this class is an abstract class. When abstract is used to modify a method, this method is an abstract method.
2. Classes containing abstract methods must be defined as abstract classes,Abstract classes must be inherited and abstract methods must be overwritten.
3. abstract classes cannot be instantiated and can only be inherited by quilt classes.
4. Abstract METHODS only need to be declared without implementation. abstract methods do not have method bodies.
For example, define a Shape. java file under the same package.
Public abstract class Shape {System. out. println ("initialization block for executing Shape");} // defines an abstract Method for Calculating perimeter public abstract double calPerimeter (); // define an abstract method for returning the shape public abstract String getTyp ();}
Define another Triangle. java File
Public class Triangle extends Shape {// defines three sides of private double a; private double B; private double c; public Triangle (double a, double B, double c) {this. setSides (a, B, c);} public void setSides (double a, double B, double c) {if (a> = B + c & B> = a + c & c> = B + a) {System. out. println ("invalid triangle"); return;} this. a = a; this. B = B; this. c = c ;}// rewrite the abstract method of the perimeter of the parent class calculation @ Override public double calPerimeter () {return a + B + c ;} // Override the returned shape of the parent class @ Override public String getTyp () {return "Triangle";} public static void main (String [] args) {Shape s1 = new Triangle (3, 4, 5); // output 12.0
System. out. println (s1.calPerimeter ());}
Abstract class:
/* Self-summary */
If different subclass classes need to call the same method from the parent class, for example, they all need to calculate the perimeter, call the calPerimeter () method from the shape parent class, but circle) the method for calculating the perimeter is not the same as that for a triangle (triangle). If a non-abstract method with a method body is defined in a shape, it cannot meet the requirements for calculating the circumference of both the circle and the triangle. If you define shape as an abstract class and calPerimeter as an abstract method, you only need to override the calPerieter () method in the subclass.
/* Book */
From the semantic point of view, an abstract class is a parent class abstracted from multiple concrete classes, which has a higher level of abstraction. Abstract An abstract class from multiple classes with the same features and use this abstract class as the template of its subclass, thus avoiding the arbitrariness of the subclass design.