第二周自学总结

一、面向对象

  • 特点:封装、继承、多态
  • 引用:创建一个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());
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jyfp成长史

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值