引言
面向对象编程(OOP)是Java编程语言的核心特性之一,它提供了一种组织代码和模型化现实世界问题的方式。为了深入理解和掌握OOP的核心技巧,以下是一个实战题库,通过一系列具体的问题和解答来帮助你解锁OOP的核心概念。
1. 类和对象
问题1:创建一个名为
Car
的类,包含属性
brand
和
model
,以及一个方法
displayInfo
。
class Car {
String brand;
String model;
public void displayInfo() {
System.out.println(“Brand: ” + brand + “, Model: ” + model);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.brand = “Toyota”;
myCar.model = “Corolla”;
myCar.displayInfo();
}
}
问题2:解释为什么
Car
类中的
displayInfo
方法需要
this
关键字。
解答
:
this
关键字在Java中用于引用当前对象。在
displayInfo
方法中,
this
关键字用于区分局部变量和实例变量。如果没有
this
,编译器会默认使用局部变量。
2. 继承
问题3:创建一个名为
SportsCar
的类,继承自
Car
类,并添加一个属性
topSpeed
。
class SportsCar extends Car {
int topSpeed;
public void displayInfo() {
super.displayInfo();
System.out.println(“Top Speed: ” + topSpeed);
}
}
public class Main {
public static void main(String[] args) {
SportsCar mySportsCar = new SportsCar();
mySportsCar.brand = “Ferrari”;
mySportsCar.model = “Enzo”;
mySportsCar.topSpeed = 320;
mySportsCar.displayInfo();
}
}
问题4:解释
super.displayInfo()
在
SportsCar
类中的作用。
解答
:
super.displayInfo()
用于调用父类
Car
中的
displayInfo
方法。这是因为
SportsCar
类继承了
Car
类,所以它继承了
Car
的所有属性和方法。使用
super
关键字可以调用父类的方法,以便在子类中重用这些方法。
3. 封装
问题5:将
Car
类的
brand
和
model
属性改为私有,并添加公共的getter和setter方法。
class Car {
private String brand;
private String model;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.setBrand(“Toyota”);
myCar.setModel(“Corolla”);
System.out.println(“Brand: ” + myCar.getBrand() + “, Model: ” + myCar.getModel());
}
}
问题6:封装的好处是什么?
解答
:封装有助于隐藏类的内部实现细节,只暴露必要的公共接口。这提高了代码的可维护性和可读性,同时也防止了外部代码对内部状态的直接访问,有助于数据的安全。
4. 多态
问题7:创建一个名为
Vehicle
的抽象类,包含一个抽象方法
move
。然后创建两个子类
Car
和
Bicycle
,分别实现
move
方法。
abstract class Vehicle {
public abstract void move();
}
class Car extends Vehicle {
public void move() {
System.out.println(“Car is moving on the road.”);
}
}
class Bicycle extends Vehicle {
public void move() {
System.out.println(“Bicycle is moving on the path.”);
}
}
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car();
Vehicle myBicycle = new Bicycle();
myCar.move();
myBicycle.move();
}
}
问题8:解释多态的概念,并说明为什么上面的代码示例展示了多态。
解答
:多态是指允许不同类的对象对同一消息做出响应。在上面的代码中,
Vehicle
是一个抽象类,它定义了一个抽象方法
move
。
Car
和
Bicycle
类都继承自
Vehicle
并实现了
move
方法。这样,当调用
move
方法时,会根据对象的实际类型来执行相应的方法,这展示了多态性。
结论
通过这个实战题库,你可以练习和巩固Java