私人,受保护和公共访问问题 [英] private, protected and public access problem

查看:53
本文介绍了私人,受保护和公共访问问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨..

我的程序包含两个名为A和B的类。B类是A类的子类。我想创建三个只能由类A访问的int值只能由A和B访问,而不能访问其他类,并且只能由任何类访问..

这是我试过的代码..



Hi..
My program contains two classes named "A" and "B".. class "B" is a subclass of the class "A".. And I want to create three int values that can be only accessed by the class "A", can be only accessed by both "A" and "B" not other classes and can be only accessed by any class..
Here is the code I've tried..

public class myProgram
{
    public static void main(String[] args) 
    {
        System.out.println(A.y);
        System.out.println(A.z);
    }
}

class A
{
    private static int x = 10;
    public static int y = 20;
    protected static int z = 30;
}
class B extends A
{
    
}





问题是受保护的int字段z可以从myProgram类访问..但是我想让它只能从A和B类访问..而不是myProgram类..我怎么能这样做?



谢谢!



The problem is the protected int field "z" can be accessed from the "myProgram" class.. But I want to make it to be accessed only from class "A" and "B".. not "myProgram" class.. How can I do it ?

Thanks !

推荐答案

让他们成为私人会员。



http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html [ ^ ]



扩展答案:

Make 'em private members.

http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html[^]

Extended Answer:
public class MyProgram // Class names always start with a captial!
{
    private ObjectA oObjectA = new ObjectA();
    private ObjectB oObjectB = new ObjectB();

    public MyProgram()
    {
        
        System.out.println(oObjectA.y); // can be called via instance cause public
        System.out.println(oObjectB.z); // can be called via instance cause proteced
        System.out.println(oObjectB.getX()); // only way to access x

    }

    public static void main(String[] args)
    {   // just calling the constructor to break out of static
        // we do not need an instance, so we do not create one
        new MyProgram(); 
    }
    
    private class ObjectA
    {
        private int x = 10;
        public int y = 20;
        protected int z = 30;


        // to make x available 
        // if the getter is not there x is not available in other instances
        public int getX(){ 
          return x;
        }
    }
    
    private class ObjectB extends ObjectA
    {
    	// more fancy stuff
    }
}





请理解这背后的基础知识。

请在这个链接后面阅读,还有更多内容供你学习。

你的老师会发现这段代码不是你的。



Please understand the basics behind this.
Please read behind that link, there is much more for you to learn.
And your teacher will figure that this code is not yours.

这篇关于私人,受保护和公共访问问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆