JAVA 类的继承(1)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/A_yuaaaaa/article/details/83180930

JAVA 类的继承(1)

10.19

使用类继承时

1.子类中有和父类相同的成员变量,则会隐藏父类成员变量

2.子类中有和父类同名、同类型、同参数的方法,则会覆盖父类中的方法

3.子类对象可以赋值给父类对象

//父类Person
    class Person
    {
     public int age;
     public String name;
     Person()
     {
      age = 5;
      name = "Father";
     }
       void Describle()
     {
      System.out.println("This is father."+" Age:"+age+" Name:"+name);
     }
       }
       
//子类Son
public class Son extends Person
{
 public String roommate;
 public int age;
 Son()
 {
  this.age = 15;
  this.name = "Son";
  roommate = "Ann";
  System.out.println("This is son."+" Age:"+age+" Name:"+name+" Roommate:" + roommate);
 } 
 void Describle()
 {
  System.out.println("This is son."+" Age:"+age+" Name:"+name+" Roommate:" + roommate);
 }
 void NewDescrible()
 {
  System.out.println("This is new son.");
 }
 public static void main(String[] args)
 {
  Person first = new Person();
 Son second = new Son(); 
  first.Describle();
  second.Describle();
  second.NewDescrible();
  first = second;
  first.Describle();
 }
 }

输出结果
 输出结果
 第一行 父类对象调用父类方法
第二行 子类对象调用的方法以及覆盖了同名、同类型、同参数的父类方法
第三行 子类对象调用子类方法
第四行 子类对象赋值给父类对象,调用Describle()方法,可见此时该对象调用的是子类中的Describle()方法

猜你喜欢

转载自blog.csdn.net/A_yuaaaaa/article/details/83180930