java 继承 讲解

来源:互联网 发布:剑灵人女捏脸数据图文 编辑:程序博客网 时间:2024/06/05 07:07


//类前面加final 类不能被继承  、成员变量前面加final 他就是常量 、方法前加final 那么他不能被覆盖和重写
class Person{
  private final int a;//常量 要在每个构造方法中都要初始化
  private final int b = 11;//常量
  private static final int c = 22;//静态常量必须在声明的时候就初始化
  private  int age;
  public  String name = "unknown";
  private int sex;
 
  public int getAge() {
    return age;
  }


  public String getName() {
    return name;
  }


  public int getSex() {
    return sex;
  }


  public void setAge(int age) {
    this.age = age;
  }


  public void setName(String name) {
    this.name = name;
  }


  public void setSex(int sex) {
    this.sex = sex;
  }
  
  /**
   * 
   *方法前加final 那么他不能被覆盖和重写
   * @param    
   * @return void
   * @throws
   * @da
   */
 public final void getInfos(){
    
  }
  


  /**
   * 无参构造函数
   */
    public Person() {
      this.a = 1;
    }
  
  /**
   * 有参构造函数  如果添加了有参构造函数就要添加无参构造函数
   *
   * @param age
   * @param name
   * @param sex
   */
/*  public Person(int age, String name, int sex) {
    super();
    this.age = age;
    this.name = name;
    this.sex = sex;
  }*/
  public Person(int a, int age, String name, int sex) {
    super();
    this.a = a;
    this.age = age;
    this.name = name;
    this.sex = sex;
  }




  public void getInfo(){
    System.out.println("父类");
  }




  
}


class Student extends Person{
  private String school = "unknown";
  private int num;
  
  public Student() {
   // super();//默认调用父类无参构造函数 
    super(1,13,"张三",10);//调用父类的有参构造函数
  }
  
  
  public Student(String name){
    super(1,13,"张三",10);
  }
  /**
   * 子类有参构造函数
   *
   * @param school
   * @param num
   */
  public Student(String school, int num,String name) {
    // super();//默认调用父类无参构造函数 
    //super(13,"张三",10);//调用父类的有参构造函数
    this("李四");
    this.name = name;
    this.school = school;
    this.setSex(1);
    this.num = num;
  }


/**
 * 重写父类的方法
 */
  public void getInfo(){
    System.out.println("zi类");
    super.getInfo();//调用父类的方法
  }


  public String getSchool() {
    return school;
  }


  public int getNum() {
    return num;
  }


  public void setSchool(String school) {
    this.school = school;
  }


  public void setNum(int num) {
    this.num = num;
  }
  
 
}






/**
 * 测试类
 */
public class Tests {
public static void main(String[] args) {
    Student std = new Student();
    std.setSchool("北京大学");
    std.setNum(99);
    System.out.println(std.getAge()+"  "+std.getName()
        +"  "+std.getSchool()
        +"  "+std.getSex()
      );
    std.getInfo();
    System.out.println(Float.MIN_VALUE);//最大的浮点小数
  }

}


打印结果:

13  张三  北京大学  10
zi类
父类
1.4E-45

0 0