继承与方法重写

提纲:1.继承的语法格式
      2.方法重写
      3.自动转型
     

1.继承的语法格式:
  1.1继承的关键字:extends

格式:
public class 类名(子类,超类,派生类) extends 类名(父类,基类) {

}
  1.2子类继承父类属性和方法的情况
    a.子类和父类在同一个包下,能调用的方法和属性:
只有私有的属性和方法不能在子类中和子类的对象调用。
    b.子类和父类不同包,能调用的属性和方法:
子类中:  公有的,受保护的属性和方法
子类的对象:公有的属性和方法
  
packge stu;   
public class Student {   
  
    //定义两个属性   
    public String name;   
    private int score;   
       
    /**  
     * 构造方法  
     */  
    public Student(){   
        this("王五",5)       
    /**  
     * 构造方法   给属性赋值初始值  
         */  
    public Student(String name,int score){   
        //赋值   
        this.name = name;   
        this.score = score;   
    }   
    public void setName(String name){   
        this.name = name;   
    }   
    public String getName(){   
        return name;   
    }   
    public void setScore(int score){   
        this.score = score;   
    }   
    public int getScore(){   
        return score;   
    }   
    /**  
     * 定义学习方法  
     */  
    public void study(){   
        score++;   
        System.out.println(name+"学习中,学分是"+score);   
    }   
}  

    
        其子类:
   
/**  
 * 定义一个UNStudent类,该类继承自Student  
 */  
public class UNStudent extends Student {   
       
    public void test(){   
        System.out.println("UNStudent Test");   
    }   
} 



2.方法重写:(注意区分它与方法重载)
   2.1条件:
1.必须要存在继承关系
2.返回值数据类型 ,方法名,参数个数,参数类型,参数顺序必须要和父类的完全一致  。
3.子类重写方法的访问修饰符可以大于或者等于父类方法的访问修饰符。
   2.2怎么调用重写的方法:
优先调用子类的方法,如果子类没有,则调用父类的.



3.自动转型:
   3.1条件:要实现自动转型就必须要存在继承关系。
   3.2格式一:
父类名 对象名 = new 子类构造方法();
Student stu = new UNStudent();

 

      格式二:
public 返回值数据类型  方法名(父类名 对象名){
对象名.调用父类中定义过的方法();
}

父类名 对象名A = new 子类构造方法();
子类名 对象名B = new 子类构造方法();

方法名(对象名A);
方法名(对象名B);

你可能感兴趣的:(java)