题目:
创建一个带有public, private, protected和包访问权限域以及方法成员的类。创建该类的一个对象,看看在你试图调用所有类成员时,会得到什么类型的编译信息。请注意,处于同一个目录中的所有类都是默认包的一部分。
解答:
在同一个package下:(调用类成员函数)
package six;
public class fiveExercise {
public int a;
private int b;
protected int c;
int d;
public void f1() {
System.out.println("This is the f1() function with public");
}
private void f2() {
System.out.println("This is the f2() function with private");
}
protected void f3() {
System.out.println("This is the f3() function with protected");
}
void f4() {
System.out.println("This is the f4() function");
}
public static void main(String[] args){
fiveExercise five = new fiveExercise();
five.a = 1;
five.b = 2;
five.c = 3;
five.d = 4;
five.f1();
five.f2();
five.f3();
five.f4();
}
}
输出结果:
在同一个package 下:(不同的类文件)
package six;
public class fiveExerciseOther {
public static void main(String[] args) {
fiveExercise fiveOther = new fiveExercise();
fiveOther.a =1;
// fiveOther.b = 2; // 因为b 是 private 成员
fiveOther.c = 3;
fiveOther.d = 4;
System.out.println("This is the fiveExerciseOther class");
fiveOther.f1();
// fiveOther.f2(); // 因为 f2() 是 private 成员
System.out.println("This is the fiveExerciseOther class");
fiveOther.f3();
System.out.println("This is the fiveExerciseOther class");
fiveOther.f4();
}
}
结果如下:
在不同的package下:
public class fiveExerciseOut {
public static void main(String[] args) {
fiveExercise fiveOut = new fiveExercise();
fiveOut.a =1;
// fiveOut.b = 2; // 因为b 是 private 成员
// fiveOut.c = 3; // 因为 c 是 protected 成员
// fiveOut.d = 4; // 因为在不同的package, 不能调用
fiveOut.f1();
// fiveOut.f2(); // 因为 f2() 是 private 成员
// fiveOut.f3(); // 因为 f3() 是 protected 成员
// fiveOut.f4(); // 因为在不同的package, 不能调用
}
}
如果觉得不错,就用点赞或者关注或者留言来代替五星好评~
谢谢各位~