Abstract classes and interfaces - JAVA

Posted by pstevereynolds on Fri, 04 Mar 2022 17:10:04 +0100

1. Abstract class
1.1 abstract class concept
In the concept of object-oriented, all objects are described by classes, but conversely, not all classes are used to describe objects
A class does not contain enough information to describe a specific object. Such a class is an abstract class
1.2 abstract class syntax
In Java, if a class is modified by abstract, it is called abstract class, and the methods modified by abstract in abstract class are called abstract methods. Abstract methods do not
The specific implementation is given in
 

// Abstract class: a class modified by abstract
public abstract class Shape {
// Abstract method: a method modified by abstract without method body
abstract public void draw();
abstract void calcArea();
// Abstract classes are also classes. You can also add common methods and properties
public double getArea(){
return area;
} p
rotected double area; // the measure of area
}

Note: an abstract class is also a class. It can contain ordinary methods, properties, or even construction methods
1. Abstract classes cannot instantiate objects directly
 

Shape shape = new Shape();
// Compilation error
Error:(30, 23) java: Shape It's abstract; Cannot instantiate

2. Abstract methods cannot be private

abstract class Shape {
abstract private void draw();
} /
/ Compilation error
Error:(4, 27) java: Illegal modifier combination: abstract and private

Note: when the abstract method is not added with an access qualifier, it defaults to public
3. Abstract methods cannot be modified by final and static because they need to be overridden by subclasses
 

public abstract class Shape {
abstract final void methodA();
abstract public static void methodB();
} /
/ Compilation error:
// Error:(20, 25) java: illegal modifier combination: abstract and final
// Error:(21, 33) java: illegal modifier combination: abstract and static

4. The abstract class must be inherited, and the subclass must override the abstract method in the parent class after inheritance. Otherwise, the subclass is also an abstract class and must be decorated with abstract

// Rectangular class
public class Rect extends Shape {
private double length;
private double width;
Rect(double length, double width){
this.length = length;
this.width = width;
} p
ublic void draw(){
System.out.println("rectangle: length= "+length+" width= " + width);
} p
ublic void calcArea(){
area = length * width;
}
} /
/ Circle type:
public class Circle extends Shape{
private double r;
final private static double PI = 3.14;
public Circle(double r){
this.r = r;
} p
ublic void draw(){
System.out.println("Circle: r = "+r);
} p
ublic void calcArea(){
area = PI * r * r;
}
} /
/ Triangle class:
public abstract class Triangle extends Shape {
private double a;
private double b;
private double c;
@Override
public void draw() {
System.out.println("triangle: a = "+a + " b = "+b+" c = "+c);
} /
/ Triangle: right triangle, isosceles triangle, etc. you can continue to refine
//@Override
//double calcArea(); //  Compilation failure: either implement the abstract method or design the triangle as an abstract class
}

5. Abstract classes do not necessarily contain abstract methods, but classes with abstract methods must be abstract classes
6. There can be construction methods in the abstract class for initializing the member variables of the parent class when the child class creates an object
1.3 function of abstract class
The abstract class itself cannot be instantiated. If you want to use it, you can only create subclasses of the abstract class Then let the subclass override the abstract method in the abstract class
Some students may say that ordinary classes can also be inherited and ordinary methods can also be rewritten. Why do you have to use abstract classes and abstract methods?
Such is the case. However, the use of abstract classes is equivalent to an extra check of the compiler
The scenario of using abstract classes is like the above code. The actual work should not be completed by the parent class, but by the child class At this time, if you accidentally misuse it as a parent class,
Using a common class compiler will not report an error However, if the parent class is an abstract class, it will prompt an error when instantiating, so that we can find the problem as soon as possible
The meaning of many grammars is to "prevent errors". For example, final, which we used to use, is similar If you don't modify the created variables, you can't change them
Is it equivalent to a constant? But in addition, final can let the compiler remind us in time when it is accidentally modified
Making full use of compiler verification is very meaningful in practical development
Interface

An interface is a public code of conduct. When you implement it, you can use it as long as it meets the standard.
In Java, an interface can be regarded as a public specification of multiple classes and a reference data type.
The definition format of the interface is basically the same as that of the definition class. By replacing the class keyword with the interface keyword, an interface is defined.
 

public interface Interface name{
// Abstract method
public abstract void method1(); // public abstract is a fixed collocation and can not be written
public void method2();
abstract void method3();
void method4();
// Note: in the interface, the above writing methods are abstract methods. Compared with recommended method 4, the code is more concise

Tips:
1. When creating an interface, the name of the interface generally starts with the capital letter I
2. The naming of the interface generally uses the word of "adjective"
3. Alibaba code specification stipulates that methods and attributes in the interface should not be decorated with any symbols to keep the code concise
2.1 interface usage
The interface cannot be used directly. There must be an "implementation class" to "implement" the interface and implement all abstract methods in the interface
 

public class Class name implements Interface name{
// ..
}

Note: the subclass and parent class are inherited by extensions, and the class and interface are implemented by implements
 

// USB interface
public interface USB {
void openDevice();
void closeDevice();
} /
/ Mouse class, implementation USB Interface
public class Mouse implements USB {
@Override
public void openDevice() {
System.out.println("Open the mouse");
} @
Override
public void closeDevice() {
System.out.println("Turn off the mouse");
} p
ublic void click(){
System.out.println("Mouse click");
}
} /
/ Keyboard class, implementation USB Interface
public class KeyBoard implements USB {
@Override
public void openDevice() {
System.out.println("Open keyboard");
} @
Override
public void closeDevice() {
System.out.println("turn off keyboard");
} p
ublic void inPut(){
System.out.println("keyboard entry");
}
} /
/ Notebook class: use USB equipment
public class Computer {
public void powerOn(){
System.out.println("Turn on the laptop");
} p
ublic void powerOff(){
System.out.println("Turn off the laptop");
} p
ublic void useDevice(USB usb){
usb.openDevice();
if(usb instanceof Mouse){
Mouse mouse = (Mouse)usb;
mouse.click();
}else if(usb instanceof KeyBoard){
KeyBoard keyBoard = (KeyBoard)usb;
keyBoard.inPut();
} u
sb.closeDevice();
}
} /
/ Test class:
public class TestUSB {
public static void main(String[] args) {
Computer computer = new Computer();
computer.powerOn();
// Using mouse devices
computer.useDevice(new Mouse());
// Using keyboard devices
computer.useDevice(new KeyBoard());
computer.powerOff();
}
}

2.2 interface characteristics
1. The interface type is a reference type, but it cannot directly the object of the new interface
 

public class TestUSB {
public static void main(String[] args) {
USB usb = new USB();
}
} /
/ Error:(10, 19) java: day20210915.USB It's abstract; Cannot instantiate

2. Every method in the interface is a public abstract method, that is, the method in the interface will be implicitly specified as public abstract (it can only be public)
abstract, other modifiers will report errors
 

public interface USB {
// Error:(4, 18) java: the modifier private is not allowed here
private void openDevice();
void closeDevice();
}

3. The methods in the interface cannot be implemented in the interface, and can only be implemented by the class that implements the interface
 

public interface USB {
void openDevice();
// Compilation failed: because the mode in the interface defaults to abstract method
// Error:(5, 23) java: an interface abstract method cannot have a body
void closeDevice(){
System.out.println("close USB equipment");
}
}

4. When rewriting the method in the interface, you cannot use the default access right modifier
 

public interface USB {
void openDevice(); // The default is public
void closeDevice(); // The default is public
} p
ublic class Mouse implements USB {
@Override
void openDevice() {
System.out.println("Open the mouse");
} /
/ ...
} /
/ Compilation error, rewrite USB in openDevice Method, the default modifier cannot be used
// Attempting to assign lower access rights; Previously public

5. The interface can contain variables, but the variables in the interface will be implicitly specified as public static final variables
 

public interface USB {
double brand = 3.0; // Default modified by: final public static
void openDevice();
void closeDevice();
} p
ublic class TestUSB {
public static void main(String[] args) {
System.out.println(USB.brand); // It can be accessed directly through the interface name, indicating that it is static
// Compilation error: Error:(12, 12) java: unable to allocate value for final variable brand
USB.brand = 2.0; // Description brand has final attribute
}
}

6. Static code blocks and construction methods are not allowed in the interface
 

public interface USB {
// Compilation failed
public USB(){
} {
} // Compilation failed
void openDevice();
void closeDevice();
}

7. Although the interface is not a class, the suffix format of bytecode file after interface compilation is also the same class
8. If the class does not implement all the abstract methods in the interface, the class must be set as an abstract class
9. jdk8: the interface can also contain the default method.
2.3 # realize multiple interfaces
In Java, there is single inheritance between classes. A class can only have one parent class, that is, multiple inheritance is not supported in Java, but a class can implement multiple connections
Mouth. Below is a group of animals represented by classes
 

class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
}
interface IFlying {
void fly();
} i
nterface IRunning {
void run();
} i
nterface ISwimming {
void swim();
}
class Cat extends Animal implements IRunning {
public Cat(String name) {
super(name);
} @
Override
public void run() {
System.out.println(this.name + "Running on four legs");
}
}
class Fish extends Animal implements ISwimming {
public Fish(String name) {
super(name);
} @
Override
public void swim() {
System.out.println(this.name + "He is swimming with his tail");
}
}
class Frog extends Animal implements IRunning, ISwimming {
public Frog(String name) {
super(name);
} @
Override
public void run() {
System.out.println(this.name + "Jumping forward");
} @
Override
public void swim() {
System.out.println(this.name + "He is kicking his legs to swim");
}
}

Note: when a class implements multiple interfaces, the abstract methods in each interface must be implemented, otherwise the class must be set as an abstract class
The above code shows the most common usage in Java object-oriented programming: a class inherits a parent class and implements multiple interfaces at the same time
In Java, there is single inheritance between classes. A class can implement multiple interfaces, and interfaces can inherit from each other. That is, multiple interfaces can be used
The purpose of inheritance.
Interface can inherit an interface to achieve the effect of reuse Use the extends keyword
 

interface IRunning {
void run();
} 
interface ISwimming {
void swim();
}
interface IAmphibious extends IRunning, ISwimming {
}

2.4 interface application examples
Sort an array of objects
 

class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
} @
Override
public String toString() {
return "[" + this.name + ":" + this.score + "]";
}
}
Give an array of student objects, Sort the elements in this object array(In descending order of scores).
Student[] students = new Student[] {
new Student("Zhang San", 95),
new Student("Li Si", 96),
new Student("Wang Wu", 97),
new Student("Zhao Liu", 92),
};
According to our previous understanding, We have a ready-made array sort method, Can you use this method directly?
Arrays.sort(students);
System.out.println(Arrays.toString(students));
// Run error, throw exception
Exception in thread "main" java.lang.ClassCastException: Student cannot be cast to
java.lang.Comparable
 Think carefully, Not hard to find, It's different from ordinary integers, Two integers can be compared directly, The size relationship is clear. What is the size relationship between the two student objects
 Are you sure? We need to specify additional.
Let's Student Class implementation Comparable Interface, And realize the compareTo method
class Student implements Comparable {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
} @
Override
public String toString() {
return "[" + this.name + ":" + this.score + "]";
} @
Override
public int compareTo(Object o) {
Student s = (Student)o;
if (this.score > s.score) {
return -1;
} else if (this.score < s.score) {
return 1;
} else {
return 0;
}
}
}
stay sort Method is called automatically compareTo method. compareTo The parameter is Object , In fact, what is introduced is Student Object of type.
Then compare the size relationship between the current object and the parameter object(According to the score).
If the current object should precede the parameter object, Returns a number less than 0;
If the current object should be placed after the parameter object, Returns a number greater than 0;
If the current object and the parameter object are in no order, Return 0;
Execute the procedure again, The results are in line with expectations.
// results of enforcement
[[Wang Wu:97], [Li Si:96], [Zhang San:95], [Zhao Liu:92]]
matters needing attention: about sort Method, Each object passed in needs an array "Comparable" of, Need to have compareTo Such ability. adopt
 rewrite compareTo Method mode, You can define comparison rules.
In order to further deepen the understanding of the interface, We can try to achieve one by ourselves sort Method to complete the sorting process just now(Use bubble sort)
public static void sort(Comparable[] array) {
for (int bound = 0; bound < array.length; bound++) {
for (int cur = array.length - 1; cur > bound; cur--) {
if (array[cur - 1].compareTo(array[cur]) > 0) {
// Explain that the order does not meet the requirements, and exchange the position of two variables
Comparable tmp = array[cur - 1];
array[cur - 1] = array[cur];
array[cur] = tmp;
}
}
}
}
Execute the code again
sort(students);
System.out.println(Arrays.toString(students));
// results of enforcement
[[Wang Wu:97], [Li Si:96], [Zhang San:95], [Zhao Liu:92]]

Topics: Java Class