super和this使用举例,以及方法覆盖和重载举例

来源:互联网 发布:淘宝活动页面代码 编辑:程序博客网 时间:2024/05/19 04:52

super和this两者都属于构造器的部分


一、使用方法:

   this: 1、this.属性  2、this.方法   3、this(参数)  

 注意----》(1)属性或者方法不能是静态的,因静态的方法或属性不属于类的实例!

   (2)属性只能是本类的属性,方法可以是父类的方法

        super:  1、super.方法   2、super(参数1,参数2,……)

注意 ----》(1)如果super和this关键字都在构造方法中出现,那么this一定是放在最前面


二、使用举例

1、新建父类:AnimalInfo.java

public class AnimalInfo {
private String color;
private String type;

public AnimalInfo(){
System.out.println("父类的无参构造方法!");
}
public AnimalInfo(String color, String type) {
this.color = color;
this.type = type;
System.out.println("父类的有参构造方法结果:打印颜色:"+color+";类型:"+type);
}

/**
 * 重载:要求返回值类型、方法名称一致而参数列表必须不同,访问修饰符不限制
 * 
 */
public void eat(){
System.out.println("父类的吃方法!");
}
protected void eat(String width){}
void eat(String width,String height){}

/*动物叫方法*/
public void song(){
System.out.println("父类的叫方法!");
}
}

2、新建子类:DogInfo.java

public class DogInfo extends AnimalInfo {
    String name;

    /**

      *覆盖:要求方法名称必须一致,访问修饰符限制必须一致或者范围更宽
     */

    /*如果构造方法不添加访问修饰符,那么就是默认(default)*/
    DogInfo() {
    this("狗二");
    System.out.println("子类无参构造方法");
    super.eat();//如果遇到this关键字,它就必须承让了,放在第二行
   this.eat();
    }
    /**覆盖构造方法,覆盖只发生在构造方法中*/
    DogInfo(String input) {
    //必须放在构造方法的第一行
    super("blue","dog");
     // super(); //必须放在构造方法的第一行
       name = input;
   }

    private DogInfo(String out,String in){ } 
    DogInfo(String out,String in,String error){  } 
}


3、新建测试类:TestMethod.java

public class TestMethod{

    public static void main(String args[]) {
//     AnimalInfo an=new AnimalInfo();
    DogInfo dog2 = new DogInfo();
    DogInfo dog1 = new DogInfo("狗一");
        System.out.println(dog1.name + ";" + dog2.name);
        /**打印结果:
       父类的有参构造方法结果:打印颜色:blue;类型:dog
父类的有参构造方法结果:打印颜色:blue;类型:dog
父类的吃方法!
父类的吃方法!
狗一;狗二
        */

    }

}


1 0
原创粉丝点击