一、面向对象
- 特点:封装、继承、多态
- 引用:创建一个Car类,在测试类中用.来调用类中的数据和成员函数
public class Test1 {
public static void main(String[] args) {
Car c1=new Car();
Car c2=new Car();
c1.brand="Hong";
c1.color="h";
c1.speed=66;
c1.go();
c1.stop();
c2.go();
}
}
- 构造方法:无返回值,一个类中必须有构造方法,若是自己不定义编译器会自动定义,构造方法名字与类名相同。
- 如下有了构造方法后图一中的引用数据可以不写,变成Car c1=new Car(“宏”,“红”,160)
public class Car {
String brand;
String color;
double speed;
//构造方法
public Car(String brand,
String color,
double speed) {
//必须有同名局部变量,必须用this.xxx来访问成员变量
this.brand=brand;
this.color=color;
this.speed=speed;
}
public void go(){
System.out.println(brand+color+"汽车跑"+speed+"m/s");
}
public void stop() {
System.out.println(brand+color+"汽车停止");
}
}
- this在构造重载(同名不同参)时可以用this(...)的形式来代替每个方法内的this.引用
public Student(int id,String name) {
/*this.id=id;
this.name=name;*/
this(id,name,null);//gender是字符串所以用null
}
public Student(int id,String name,String gender) {
/*this.id=id;
this.name=name;
this.gender=gender;*/
this(id,name,gender,0);//age是int型所以用0
}
//从构造方法,调用另一个重载的构造方法
//目的是减少代码重复
public Student( int id,
String name,
String gender,
int age) {
this.age=age;
this.gender=gender;
this.id=id;
this.name=name;
}
- 继承:代码重用、代码复用。可以在子类中重写父类方法,当子类有方法时先执行子类的。 不继承:构造方法、私有成员、静态成员
- 要执行父类构造方法可以使用super(),super.xxx()用来调用父类成员方便重写
public Point3D(int x,int y,int z) {
/*this.x=x;
this.y=y;*/
super(x,y);//手动调用父类有参构造
this.z=z;
}
- 多态:作用是一致类型,在一定情况下把子类型当做父类型处理,需要向上转型,必要时在转回子类型完成向下转型
public class Test3 {
public static void main(String[] args) {
f(new Point(3,4));
f(new Point3D(3,4,5));//多态:子类对象向上传递,转型成父类型传递到f
}
static void f(Point p) {
System.out.println(p.toString());
System.out.println(p.distance());
}
}