我们来举个例子:文件名是:Inherite.java
class Person{
String name;
protected int age;
}
class Student extends Person{
String school;
double score;
}
public class Inherite {
public static void main (String [] argv ){
Student S = new Student ();
S.name = "卓增泗";
S.school = "交通大学";
S.age = 24;
S.score = 95.5;
System.out.println("我是" + S.name + ",今年" + S.age + "岁,毕业于" + S.school + ",平均成绩是:" + S.score);
}
}
最终的结果是:
这个结果说明,子类是可以访问父类的default型的成员变量的。但是,当它们不在同一包中呢?我们再举一个例子:文件名1:Person.java 文件名2:Inherite1.java
//文件1:Person.java
package heri;
public class Person {
String name;
public int age;
}
这个文件编译后*.class文件位于heri文件夹中,编译命令为:javac -d . Person.java
//文件名:Inherite1.java
class Student extends Person{
String school;
double score;
}
public class Inherite1 {
public static void main (String [] argv ) {
Student S = new Student ();
S.name = "卓增泗";
S.school = "交通大学";
S.age = 24;
S.score = 95.5;
Syste