Java面向对象 第三章
- 包
(1)使用其他包中的类是需要import导入包
import pakegeName.clssName;
(2)访问修饰符
public:公共的,任何包下的内容都可以访问
缺省:默认只能被当前包访问
private:只被当前类访问
protected:只能当前包和不同包的子类访问
练习
1.测试public,private,protected,缺省访问修饰符的访问范围
package com.schools;
public class Schools {
private String name;
private int established;
protected void setName(String name) {
this.name = name;
}
protected void setEstablished(int established) {
this.established = established;
}
protected String getName() {
return name;
}
protected int getEstablished() {
return established;
}
}
package com.test;
import com.schools.Schools;
public class Test extends Schools {
public static void main(String[] args) {
Test s = new Test();
System.out.printf("%s,%d", s.getName(), s.getEstablished());
}
}
(1)父类中的protected只能通过子类的对象访问
(2)protected只能被当前类和当前类的子类访问
(3)private只能被当前类访问
(4)缺省只能被当前包访问
2.练习使用继承
public class Vehicles {
String brand;
String color;
public Vehicles(String brand, String color) {
this.brand = brand;
this.color = color;
}
public void showVehicles() {
System.out.printf("品牌:%s\t颜色:%s\n", brand, color);
}
public void run() {
System.out.printf("%s正在行驶!\n", brand);
}
}
public class Truck extends Vehicles {
float load;
public Truck(String brand, String color, float load) {
super(brand, color);
this.load = load;
}
public void showCar() {
System.out.printf("我是一辆:%s\t我的颜色:%s\t我的载重:%.1f吨的材料\n", brand, color, load);
}
}
public class Car extends Vehicles {
int seats;
public Car(String brand, String color, int seates) {
super(brand, color);
this.seats = seates;
}
public void showCar() {
System.out.printf("我是一辆:%s\t我的颜色:%s\t我有:%d个座位\n", brand, color, seats);
}
}
public class Test {
public static void main(String[] args) {
Car c = new Car("迈巴赫", "黑色", 4);
c.showVehicles();
c.showCar();
c.run();
System.out.println();
Truck t = new Truck("东风", "红色", 1433.66f);
t.showVehicles();
t.showCar();
t.run();
}
}