title: Abstract Methods and Classes Interfaces
date: 2023-11-07
author:
- AllenYGY
status: DONE
tags:
- NOTE
- Java
- Lec5
- Program
created: 2023-11-07T00:59
updated: 2024-05-31T00:40
publish: True
Abstract Methods and Classes Interfaces
public class Test {
public static void main(String[] args) {
// Cannot instantiate the type shape
Shape s = new Shape(); // Forbidden
Circle c = new Circle(); // Okay
Shape sc = new Circle(); // Okay
}
}
An interface is specified using the interface keyword.
public interface xxx {}
It is not possible to create an object from an interface 因为接口是抽象方法的集合,所以可以类比抽象类,所以无法创建对象
接口不是类
A class specifies that it implements an interface using the implements keyword.
public class xxx implements xxx {}
public interface Movable {
public double getSpeed();
public void setSpeed(double newSpeed);
public static final int MY_CONSTANT = 100;
//在上面的示例中,MY_CONSTANT是一个常量,它被声明为public static final,这意味着它是一个公共的、静态的和不可变值。
}
public class Car extends Vehicle implements Movable {
@Override
public double getSpeed() { }
@Override
public void setSpeed(double newSpeed) { }
}
public abstract class Car extends Vehicle implements Movable {
/*
* Does not implement setSpeed method, leave it to a
* subclass to implement the missing method
*/
@Override
public double getSpeed() { }
}
public class SmallCar extends Car {
@Override
public void setSpeed(double newSpeed) {
// Implement the missing method
}
}
public interface Movable {
public double getSpeed();
public void setSpeed(double newSpeed);
}
public interface Edible {
public void cook();
}
public class Car extends Vehicle implements Movable {
@Override
public double getSpeed() { }
@Override
public void setSpeed(double newSpeed) { }
}
public class Rabbit extends Animal implements Movable, Edible {
@Override
public double getSpeed() { }
@Override
public void setSpeed(double newSpeed) { }
@Override
public void cook() { }
}
Edible e = new Rabbit(); //类比子类继承父类
e.cook(); // Cooking the rabbit.
public class Test {
public void stopMovable(Movable m) {
m.setSpeed(0.0); // m’s speed is now zero.
}
}
The stopMovable method stops a movable object, but it does not know whether the movable object is a car or a rabbit. It only knows that the object is movable (which is really the only thing it needs to know).
An interface splits your software into two parts:
The classes that implement the interface do not need to know anything about how the rest of the code uses the interface. 实现时不需考虑如何使用
The rest of the code that uses the interface does not need to know anything about how the classes implementing the interface work internally. 使用时不需考虑如何实现