Java 习题 (54)

题目:
创建一个带有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, 不能调用
    }
}

如果觉得不错,就用点赞或者关注或者留言来代替五星好评~
谢谢各位~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值