java继承

代码展示了Java中子类继承父类并重写其方法的概念。当调用重写的方法时,会执行子类的版本。若需调用父类的原方法,可使用`super`关键字。由于`this`和`super`不能在静态方法中使用,因此不能在`main`方法中直接使用`super`。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值