继承的概念
class childClass extends parentClass
{
//类体
}
例子
public class Person {
public String name;
public String getName() {
return name;
}
}
public class Employee extends Person {
public int employeeNumber;
public int getEmployeeNumber() {
return employeeNumber;
}
}
public class Manager extends Employee {
public String responsibilities;
public String getResponsibilities() {
return responsibilities;
}
}
public class B {
public int a = 10;
privateintb = 20;
protected int c = 30;
public intgetB() { return b; }
}
public class A extends B {
public int d;
public void tryVariables() {
System.out.println(a); //允许
System.out.println(b); //不允许
System.out.println(getB()); //允许
System.out.println(c); //允许
}
}
–由于Java的方法调用可以忽略返回值,故不能使用返回类型来区分重载的方法
–覆写方法的访问权限可以比被覆写的宽松,但是不能更为严格
public class Ostrich extends Bird {
public void fly() {
System.out.println(“我只能在地上奔跑…”);
}
public void callOverridedMethod() {
//fly();
super.fly();
}
public static void main(String args[]) {
Ostrich os = new Ostrich();
// do something
}
}
创建子类对象时会隐式创建父类对象
class Father {
public Father() {
System.out.println(“Father Create”);
}
}
public class Child extends Father {
public Child() {
System.out.println(“Child Create”);
}
public static void main(String args[]) {
Father fa = new Fahter();
Child ch = new Child();
}
}
输出:
Father Create
Father Create
Child Create
以下方法为基类的一个方法:
void method() { }
请问以下哪些是子类中覆写该方法的正确形式?
请选择所有正确答案(多选题):
A. void method() { }
B. int method() { return 0; }
C. void method(inti) { }
D. private void method() { }
A. 方法覆写的基本原则是保持参数列表和返回值类型不变。B是错的,因为返回类型不一致。C是错的,因为参数列表不一致。D是错的,因为子类中覆写的方法缩小了访问控制范围。
隐藏和封装
因此,封装实际上有两个方面的含义:把该隐藏的隐藏起来,把该暴露的暴露出来