public class Hello extends Father{
String word2 = "世界";
public void test(){
System.out.println("使用父类变量:"+word1+word2);
}
@Override
//父类中声明为 public 的方法在子类中也必须为 public
public void hello(){
System.out.println("重写父类方法");
}
public static void main(String[] args) {
Hello dao=new Hello();
//使用父类的变量
dao.test();
//调用重写后的方法
dao.hello();
}
}
abstract class Father{
String word1="你好";
public void hello(){
System.out.println("调用了父类:"+word1);
}
}
代码中重写了父类的方法,所以我们调用的是重写后的方法,如果不重写方法,将看到以下输出
public class Hello extends Father{
String word2 = "世界";
public void test(){
System.out.println("使用父类变量:"+word1+word2);
}
public static void main(String[] args) {
//创建对象调用父类的hello方法
Hello dao=new Hello();
//使用父类的变量
dao.test();
dao.hello();
}
}
abstract class Father{
String word1="你好";
public void hello(){
System.out.println("调用了父类:"+word1);
}
}
不难看出上面两段代码的区别,但是将方法重写之后,我们调用方法将会是一直调用子类重写后的方法,它将父类的方法覆盖,那如果我们还要调用父类的方法将使用到super这个关键字。
public class Hello extends Father{
String word2 = "世界";
public void test(){
System.out.println("使用父类变量:"+word1+word2);
}
@Override
//父类中声明为 public 的方法在子类中也必须为 public
public void hello(){
System.out.println("重写父类方法");
}
public void father(){
super.hello();
}
public static void main(String[] args) {
//创建对象调用父类的hello方法
Hello dao=new Hello();
dao.father();
//使用父类的变量
dao.test();
//调用重写后的方法
dao.hello();
}
}
abstract class Father{
String word1="你好";
public void hello(){
System.out.println("调用了父类:"+word1);
}
}
在上面的代码可以是在子类创建了一个方法来调用父类的方法,并不是在主方法里面直接调用,这是因为java中的语法规定:this和super都不能在静态方法中使用,所以不能在main中使用super。