1. 重载和重写:
- 重载(Overload): 方法重载是让类以统一的方式处理不同类型数据的一种手段。多个同名函数同时存在,具有不同的参数个数/类型。
public void print() {
System.out.println("Hello message");
}
// 相同方法名,不同参数
public void print(String msg) {
System.out.println("The message is " + msg);
}
// 相同方法名,不同返回类型和参数
public int print(int number) {
System.out.println("The number is " + number);
}
- 重写(Override):为了实现继承的多态性,子类不想完全继承父类的方法;如果在子类中定义某方法与其父类有相同的名称和参数,我们说该方法被重写
class Father {
public void calculate(int a, int b) {
int result = a + b;
System.out.println(result);
}
}
class Son extends Father {
// 相同方法名和参数,不同
@Override
public void calculate(int a, int b) {
int result = a * b;
System.out.println(result);
}
}
2. 类型转换:
-
自动转型 -- 子类向上转型为父类,属于安全
public class Father {
static String name = "Father";
int age = 35;
public void print() {
System.out.println("I'm a father");
}
public static void showInfo() {
System.out.println("I'm " + age + "years old");
}
}
class Son extends Father {
static String name = "Son";
int age = 5;
@Override
public void print() {
System.out.println("I'm a son");
}
public static void showInfo() {
System.out.println("I'm " + age + "years old");
}
}
编译和运行:
public static void main (String[] args) {
Son son = new Son();
Father father = new Son(); // 子类自动转型为父类
// 静态属性
System.out.println(son.name);
System.out.println(father.name);
// 非静态属性
System.out.println(son.age);
System.out.println(father.age);
// 非静态方法运行
son.print();
father.print();
// 静态方法运行
son.showInfo();
father.showInfo();
}
结果显示为:
Son
Father
5
35
I'm a son
I'm a son
I'm 5 years old
I'm 35 years old
从结果可以总结出:
1. 编译看左边:
对象father没有因为引用了子类new Son()的构造函数而输出了子类成员变量值,依旧是输出Father类的成员变量值,编译取决于“=”左边的类型
2. 运行看右边:
-- father和son对象在调用非静态方法时,运行结果都是Son子类的方法,因此运行取决于“=”右边的类型
-- 如果是调用的是静态方法,运行取决于“=”左边的类型,因为静态是随类加载的
-
强制转型 -- 父类强制向下转型为子类
// 例子1 -- 不允许强转
Father father = new Father();
Son son = (Son) father;
son.print();
// 例子2 -- 允许强转
Father father = new Son();
Son son = (Son) father;
son.print();
- 例子1会抛异常 “java.lang.ClassCastException” ,父类对象不允许直接强转为子类
- 例子2可以正常运行,只有父类对象本身就是用子类new出来的时候, 才可以在将来被强制转换为子类对象.
171万+

被折叠的 条评论
为什么被折叠?



