1,継承(inheritance)とは
あるクラスが他のクラスから属性(attributes)やメソッド(methods)を取得するプロセスです
2,ソースコード
Main.java
public class Main {
public static void main(String[] args) {
// inheritance = the process where one class acquires,
// the attrivutes and methods of another.
Car car = new Car();
car.go();
Bicycle bike = new Bicycle();
bike.stop();
System.out.println(car.speed);
System.out.println(bike.speed);
System.out.println(car.doors);
System.out.println(bike.pedals);
}
}
継承元👇
Vehicle.java
public class Vehicle {
double speed;
void go() {
System.out.println("This vehicle is moming");
}
void stop() {
System.out.println("This vehicle is stopped");
}
}
クラスからクラスへ継承する場合、”子クラス extends 親クラス” と表記します👇
Car.java
public class Car extends Vehicle {
int wheels = 4;
int doors = 4;
}
Bicycle.java
public class Bicycle extends Vehicle {
int wheels = 2;
int pedals = 2;
}