2020.10.5
今天学了重写 super 以及继承中的构造方法,为验证学习成果来做一道练习题
class A{
protected void print(String s) {
System.out.println(s);
}
A(){
print("A()");
}
public void f() {
print("A:f()");
}
}
class Test1 extends A {
Test1(){
print("Test1()");
}
public void f() {
print("Test1:f()");
}
public static void main(String[] args) {
Test1 b = new Test1();
b.f();
}
}
读以上程序,判定输出结果
简单分析一下两个类,首先是父类A,它有两个方法和一个构造方法,其中A方法无参数,f方法则调用print方法来输出字符串
之后是子类Test1,它在继承了父类的方法之后还有两个方法,其中Test1调用父类的print方法,f()方法重写了父类的f(),并且还会自动调用父类中没有参数的方法
在一顿分析之后我们可以猜到最后的结果就是:
A() //自动调用父类无参数
Test1() //调用父类中print方法
Test1:f() //重写了f()方法
下面进行程序的运行:
结果正确!
再来一道练习题
package haro;
class YesPerson{
private String name;
private String location;
YesPerson(String name){
this.name = name;
location = "beijing";
}
YesPerson(String name,String location){
this.name = name;
this.location = location;
}
public String info() {
return("name: " + name + " location: " + location);
}
}
class YesStudent extends YesPerson{
private String school;
YesStudent(String name,String school){
this(name,"beijing",school);
}
YesStudent(String n , String l ,String school){
super(n,l);
this.school = school;
}
public String info() {
return(super.info() + " school: " + school);
}
}
class YesTeacher extends YesPerson{
private String capital;
YesTeacher(String name,String capital){
this(name,"beijing",capital);
}
YesTeacher(String n , String l ,String capital){
super(n,l);
this.capital = capital;
}
public String info() {
return(super.info() + " capital: " + capital);
}
}
public class TestTeacher {
public static void main(String[] args) {
YesPerson p1 = new YesPerson("A");
YesPerson p2 = new YesPerson("B" , "shanghai");
YesStudent s1 = new YesStudent("C" , "S1");
YesStudent s2 = new YesStudent("C" , "shanghai" , "S2");
YesTeacher t1 = new YesTeacher("D" , "professor");
YesTeacher t2 = new YesTeacher("D" , "shanghai" , "principal");
System.out.println(p1.info());
System.out.println(p2.info());
System.out.println(s1.info());
System.out.println(s2.info());
System.out.println(t1.info());
System.out.println(t2.info());
}
}
这是一个我认为对于重载,重写,super,继承中构造方法很全面的程序
非常容易入手建议平时多看看