在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();
}
}