Click here to Skip to main content
14,733,890 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
{
    
}


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 !
Posted

1 solution

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.
   
v2
Comments
M­­ar­­­­k 31-Mar-14 8:09am
   
But making them private members prevent it being accessed from class B :(
I want them to be accessed from only Class A and Class be....

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900