//继承概述:当一个类与另一个类之间是一种类似于包含的关系时,我们就可以将这种关系称为继承,如
class Person{
public String name;
public int age;
}
class Student{
public String name;
public int age;
public int num;
}
class Student2 extends Person{ //(Student2继承了Person,它与Student的功能一样)
public int num;
}
class A{
A(){
System.out.println("A");
}
}
class B extends A{
B(){
System.out.println("B");
}
}
class C extends B{
C(){
System.out.println("C");
}
}
public class Text1 {
public static void main(String[] args) {
new C();
}
}//输出A B C (竖列)
多态
/**
* 多态存在的前提:
* 继承关系;
* 方法重写;
* 父类引用指向子类对象;
* 多态中成员访问特点:
* 成员变量:编译看左.运行看左;
* 成员方法(非静态):编译看左,运行看右;
* 静态成员方法:编译看左,运行看左;(静态与类有关,算不上初始化)
* 构造方法:无论子类还是父类,都是对对象进行初始化
* 多态的坏处:
* 父类引用指向子类对象;
* 父类不能使用子类的特有功能;(如果需要使用子类的特有功能需要向下转型)
*/
class Person{
public void eat() {
System.out.println("吃饭");
}
}
class Student extends Person{
public void eat() {
System.out.println("学生吃饭");
}
public void study() {
System.out.println("学生学习");
}
}
public class Text2 {
public static void main(String[] args) {
Person p = new Student();//向上转型
p.eat();
// p.study(); //不能调用子类特有功能
Student s = (Student)p;//向下转型
s.study();
}
}