网站域名建设怎么填写,程序开发的步骤,拼多多网站策划书,网站里的网页是一个一个做的么重点#xff1a;super类 方法重写
super类
super指的是本级的上一级#xff0c;即father class父类
很好理解#xff0c;比如Person classStudent class 当前在Student class执行#xff0c;那么就写this.xxx 需要在Student程序里面调用Person#xff0c;那就…重点super类 方法重写
super类
super指的是本级的上一级即father class父类
很好理解比如Person classStudent class 当前在Student class执行那么就写this.xxx 需要在Student程序里面调用Person那就写super.xxx
比如下面的例子
建立一个叫做kids的class它的上级是human class从主程序testjan05来调用kids class里面的method my_prt它可以打印输出kids class里的变量name以及this.name和super.name。注意将kids内部的name设为private观察输出的结果 public class testjan05{
public static void main(String args[]) {kids x new kids();x.my_prt(emma);}
}
public class kids extends human{private String name kids_name;public kids() {super();//这句如果用户不写也可以。这是一句隐藏指令代表去调用父类的constructor一定在子类的constructor最开始出现。//这一句就是表示在运行kids constructor的下面内容之前需要先去运行human constructor的内容。并且human constructor必须是无参的。//如果human constructor有参那么它会覆盖同名的human constructor继而引申到kids constructor也会报错参见下一例。System.out.println(这里是kids.class内部);}public void my_prt(String name) {System.out.println(name);//这里应该是my_prt从主程序来的输入信号emmaSystem.out.println(this.name);//这里因该是本级的kids_nameSystem.out.println(super.name);//human_name}} public class human {public String name human_name;public human() {System.out.println(这里是human.class内部);}}
运行结果
这里是human.class内部
这里是kids.class内部
emma
kids_name
human_name
刚才举例中介绍了当子类constructor运行时必然会首先默认跑一遍父类的constructor那句代码通常是隐藏在子类constructor第一行 写做super(); 问题思考 如果父类constructor其实被用户更改了变成了一个有参的costructor会发生什么。 tips根据之前的知识一旦出现有参的constructor它会覆盖同名的无参constructor
public class testjan05{
public static void main(String args[]) {kids x new kids();}
}
public class kids extends human{private String name kids_name;public kids() {super();//这个super是去父类human class里面调用human constructor//系统默认这个父类的constructor肯定是无参的现在人为加了参数a//这里一定会报错错误见下图System.out.println(inside kids constructor);}
} public class human {public String name human_name;public human(String a) {System.out.println(inside human constructor);//注意这里用户自定义的human constructor被用户增加了一个参数String a//原本系统在后台默默建立的无参human constructor会被用户这个有参的覆盖掉}
}
错误图示
错误提示 Expected 1 arguments but found 0
解决方法给super()添加一个符合父类human constructor要求的参数即可
public class kids extends human{private String name kids_name;public kids() {super(sth_random);//父类human constructor需要String作为输入//这里随意给了一个String立刻就不报错了System.out.println(inside kids constructor);}}
super注意点 1.super表示调用父类的构造方法肯定在构造方法的第一个出现系统会偷偷加上 2.super必须只能在子类的方法或者构造方法中 3.super 和 this不能同时调用构造方法同时写出来肯定有一个报错
super VS this:
代表的对象不同 this:本身调用的这个对象 super:代表父类对象的应用
前提 this:没有继承人也可以用 super:只能在继承条件下才可以用
构造方法的区别 this(); 本类的构造 super(); 父类的构造