需要注意的是,如果父类的方法被子类重写了,那么通过父类引用来调用该方法时,将调用子类的方法

在Java中,可以通过父类的对象来调用子类的成员。这是因为在Java中,子类继承了父类的所有属性和方法,所以子类的对象可以访问父类的所有非私有成员。
假设我们有一个父类Animal和一个子类Dog,Dog继承了Animal类。如果Animal类有一个公共方法speak(),那么我们可以通过Animal的引用调用Dog对象的speak()方法。

public class Animal {
    public void speak() {
        System.out.println("Animal speaks");
    }
}
public class Dog extends Animal {
    @Override
    public void speak() {
        System.out.println("Dog barks");
    }
}
public class Main {
    public static void main(String[] args) {
        Animal animal = new Dog();
        animal.speak(); // 输出 "Dog barks"
    }
}

在这个例子中,我们创建了一个Dog对象,并将其引用赋给Animal类型的变量animal。然后我们通过animal调用speak()方法,由于Dog类重写了该方法,所以输出的是"Dog barks"。
需要注意的是,如果父类的方法被子类重写了,那么通过父类引用来调用该方法时,将调用子类的方法。这是因为子类对象实际上是父类和子类的混合体,所以Java运行时系统会根据实际对象的类型来确定调用哪个方法。如果子类没有重写父类的方法,那么通过父类引用来调用该方法时,将调用父类的方法。
此外,如果父类和子类有同名的成员(属性或方法),那么在子类中可以通过super关键字来访问父类的同名成员。例如,如果Dog类有一个name属性,同时Animal类也有一个name属性,那么在Dog类中可以通过super.name来访问Animal类的name属性。
The java compiler (javac. Exe) and Java interpreter (Java. Exe) provided by the JDK platform are located in the bin folder of the Java installation directory. In order to use the compiler and interpreter in any directory, path should be set in the system features. For Windows 2000, windows 2003 and windows xp, right-click “my computer”, pop up the menu, then select “properties”, pop up the “system properties” dialog box, then click the “advanced” option in the dialog box, then click the button “environment variables”, and add the following system environment variables

class Person     //定义Person类
{
  protected String name;
  protected int age;
  public Person(String name, int age)  //定义构造方法
  {
    this.name=name;
    this.age=age;
  }
  protected void show()
  {
    System.out.println("姓名:"+name+"  年龄:"+age);
  }
}
class Student extends Person  //定义子类Student,其父类为Person
{
  private String department;
  public Student (String name,int age,String dep)  //定义构造方法
  {
    super(name,age);
    department=dep;
  }
  protected void show()
  {
    System.out.println("系别:"+ department);
  }
  public void subshow()
  {
    System.out.println("我在子类中");
  }
}
public class javase_17      //主类
{
  public static void main(String[] args)
  {
    Person per=new Student("java",200, "se"); //声明父类变量per指向对象
    per.show();   //利用父类对象per调用show()方法
    //per.subshow();
  }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bol5261

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值