一.包
语法:
package<包名>
使用其他包中的类是需要import导入包
import pakegeName.clssName
如果导入一个包中多个类,可以使用“*”表示包中所有类。
示例一
在com.java包中创建一个学生类,在com.test包中创建测试类test并输出学生信息
package com.java.oriented.dota.scene;
public class Test{
public static void main(String[]args){
Student stu = new Student("张三",19);
System.out.println(stu.name+"\t"+stu.age);
一个包具有缺省访问权限的成员只能在同一个包中被引用。
二.继承
子类会继承父类所有非私有成员
一个子类只能有一个父类
继承语法:
[修饰符] class 子类名 [extends 父类名]{
//类成员
示例二
创建一个交通工具父类以及两个子类,分别是小汽车类和卡车类,显示出各类的相关信息。
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);
}
}
总结:java中的继承为单继承,即一个子类只能有一个直接父类