多态
1. 重载(overload),函数名称相同,传入参数不同。
class Student{
Water getWater() {}
Water getWater(ClassmateRequest cr) {}
}
2. 覆盖(override),子类重写父类方法。
class Student{
public void study() {
///...
}
}
class LazyStudent extends Student{
public void study() {
while(true) {
sleep();
eat();
}
}
}
通常采用父类引用指向子类对象
Student s1 = new LazyStudent();
s1.study();
3. 抽象类,类中有抽象函数时,该类为抽象类,关键词:abstract.抽象类不能实例化,只能被继承。
abstract class Shape() {
abstract public double area() {
}
}
class Circle extends Shape{
double r;
public double area() {
return Math.PI * r * r;
}
}
4. 接口(interface),覆盖类中的某些方法,同时提高程序的可扩展性
public interface Record{
public abstract void a();
public abstract void b();
}
class A implements Record{
public void a() {}
public void b() {}
}
注:接口继承可以多继承,例如:
class A implements K,M,N{
}
构造函数,初始化
1.构造函数名与类名相同,无返回值,用来初始化对象属性值。
2.若不声明构造函数,编译器自动生成默认构造函数。
3.继承时,子类构造函数中默认有super();函数。
class A {
int i;
A(int x){
i = x;
}
}
class B extends A{
double j;
B(double x,int y){
super(y);
j = x;
}
}
4.this引用变量,一般不写,指向本身对象。
public class Point{
int x,y;
public Point(int x,int y) {
this.x = x;
this.y = y;
}
public Point() {
this(0,0);
}
}
5. super 和 this 只能出现在构造函数第一行。