继承与多态的问题

来源:互联网 发布:网络侦探练哪些 编辑:程序博客网 时间:2024/06/07 00:58
<pre name="code" class="java">/** * @author franky814 * @继承与多态的相关 * 1.如果多个类具有普遍相同属性或者功能,那么可以抽取其中的属性和功能建立父类,这样子类可以继承父类的基本属性或方法 * 2.子类继承父类的一般的成员变量和成员方法可以进行重写或覆盖,而且子类可以添加自身所需的特殊成员方法 * 3.子类如果覆盖父类的方法,那么返回值类型必须一致,并保证权限要大于等于父类权限,父类方法不能为private权限 * 4.在子类的构造方法中必须先执行父类的构造方法super(),如果父类显式的指定了构造方法的参数列表,那么子类也必须显式调用父类的构造方法 * 5.子类的构造方法中,this() 与 super()不能同时存在,因为this()方法中也会到父类中调用super()方法 * 6.如果子类中存在与父类中同名的成员变量那么在调用该变量时候,如果是父类引用指向子类对象(Father f = new Son()),那么该变量的值是指向父类的, *   如果是子类引用指向子类对象(Son f = new Son())那么该变量的值是指向子类的,开发中不建议使用 * 7.如果子类覆盖了父类方法,那么 父类引用指向子类对象(Father f = new Son())时候,调用该方法依然是指向子类对象的方法,而不是父类 * 8.如果是子类继承了父类的静态方法,那么可以进行重写,但是必须以类名.静态方法名的方式来访问,父类引用指向子类对象(Father f = new Son())时候, *  调用的静态方法是指向父类引用的而不是子类 * 9.在父类引用指向子类对象(Father f = new Son())中,如果子类存在与父类同名的成员变量,那么在父类方法中调用该变量, *   指向的值是父类的成员变量而不是子类 * 10.父类引用指向子类对象(Father f = new Son()) 称为 向上转型 * 11.Son s = (Son)f;将父类的引用转换为子类引用,成为 向下转型 * 12.Father f = new Father() 不能向下转换为Son对象,因为向下不确定子类是否只有Son一种类 */public class Test {public static void main(String[] args) {//父类引用指向子类对象时候,子类对象如果对继承的父类方法进行覆盖,那么将执行子类的方法Animal dog = new Dog(2, "Jerry");Animal cat = new Cat(2, "Tom");dog.setColor("red");cat.setColor("white");dog.cry();//输出:A red dog is crying!!cat.cry();//输出:A white cat is crying!!//调用Animal的静态方法看看,因为dog和cat都是Animal所以具备它们自己的cry方法Animal.crys(dog);//输出:A red dog is crying!!Animal.crys(cat);//输出:A white cat is crying!!//调用重新Dog重新写的静态方法,必须用类名调用//Dog.crys();}}/** * 定义基本父类 Animal */class Animal{int age;String name;//父类私有的变量不能被子类直接访问,必须提供公开的方法来对其进行操作private String color;public String getColor() {return color;}public void setColor(String color) {this.color = color;}public void cry(){}/** * Animal具有的基本cry功能,所以传入一只Animal,而不是具体面对某种Animal,所以提高了代码的扩展性 * @param animal 传入的一只Animal */public static void crys(Animal animal){animal.cry();}}/** *Dog实现父类Animal */class Dog extends Animal{Dog(int age,String name){super();this.age = age;this.name = name;}    //重写了父类的cry()方法public void cry(){System.out.println("A "+getColor()+" dog is crying!!");}//Dog类具有的特殊功能public void watchDoor(){System.out.println("The "+getColor()+" dog can watch door!");}//重新父类的静态方法//public static void crys(){//System.out.println("The dog is static!");//}}/** *Cat实现父类Animal */class Cat extends Animal{Cat(int age,String name){super();this.age = age;this.name = name;}//重写了父类的cry()方法public void cry(){System.out.println("A "+getColor()+" cat is crying!!");}//Cat类具有的特殊功能public void catchMouse(){System.out.println("The "+getColor()+" cat can catch mouse!");}}


                                             
0 0
原创粉丝点击