Can a object be private and public? - java

Can a reference to an object be private in class while other object can have a public reference to the same class(post script: new to java+ a simple example please).
I read somewhere that this prob is regarding aliasing?
Sorry my title may not make sense!

Objects aren't private or public. Fields can be private or public. Fields can hold references to objects. An object can be referred to by both private and public fields simultaneously:
public class Example {
public static Object a;
private static Object b;
public static void main(String... args) {
Object foo = new Object();
a = foo;
b = foo;
// Now our Object is referred to by the public field a, the private
// field b, and the local variable foo (which is not considered either
// private or public).
}
}

public and private are access modifiers. They are optional modifiers and they decides the accessibility of variables,methods or classes. If use use private modifier it means is that, the relevant member can only be accessed within the same class. If it is public you can access that member in same class, same package and different package; simply everywhere. OOAD suggest we should encapsulate what varies. So we make all the instance variable private and declare public getter/setter methods to access those variables from anywhere. public and private are just modifiers.

public and private are access modifiers. If use use private modifier it means is that, the relevant member can only be accessed within the same class. If it is public you can access that member in same class, same package and different package; simply everywhere. OOAD suggest we should encapsulate what varies. So we make all the instance variable private and declare public getter/setter methods to access those variables from anywhere. public and private are just modifiers.

Related

Static nested sub-classes of the enclosing type can still refer to the private field members, why?

I found something which is ambiguous IMHO. Lets say we have the following class structure:
public class A
{
private int privateVar = 1;
protected int protectedVar = 2;
static class B extends A
{
public int getPrivateVariable()
{
return privateVar; //error: Cannot make a static reference to the non-static field memberVariable
}
public int getProtectedVariable()
{
return protectedVar; //OK: Why?
}
public int getPrivateUnfair()
{
return super.privateVar; //Why this can be accessed using super which the protected member doesn't require.
}
}
}
Why at all does the static nested class has free access to the instance members?
Why there is a difference in the way protected and private variables can be accessed? This however, is not the case if the nested class is non-static inner class?
EDIT:
Why is the private member of the enclosing type allowed to be accessed by the keyword super?
Why at all does the static nested class has free access to the instance members?
Because B extends A. You're not accessing the member variables of A, you're accessing the inherited member variables of B.
Why there is a difference in the way protected and private variables can be accessed? This however, is not the case if the nested class is non-static inner class?
Because private fields aren't inherited, whereas protected fields are; but the private fields are still present in the superclass, and visible via super because B is nested inside A. Visibility modifiers aren't sufficiently expressive to articulate the same thing as accessing via super.
Why at all does the static nested class has free access to the instance members?
Nested classes have access to all private members in the same outer class. They are all compiled at once and accessor methods are added to allow this. Note: hte JVM doesn't allow such access which is why accessor methods need to be added.
Why there is a difference in the way protected and private variables can be accessed?
protected members are assumed to be accessed via the super class as they are inherited. Private fields are not inherited, but can be accessed for nested classes.

Is this the right definition of 'private' access modifier in java?

As per the link, definition says, The private modifier specifies that the member can only be accessed in its own class.
But the below code is able to access private member item of super class in sub class.
class SuperType {
private int item;
public void setItem(int item){
this.item = item;
}
public int getItem(){
return item;
}
}
public class SubType extends SuperType{
public static void main(String[] args){
SubType s = new SubType();
s.setItem(2);
System.out.println(s.getItem());
}
}
It is also understood that s.itemdoes not work, because item is not a member of SubType class.
How do i understand this definition?
Access modifiers affect direct access to that member.
SubType can get access to item indirectly, through the public getter method, which exists in SuperType and thus has access to the private item member variable.
But SubType can't directly access it, i.e. this is an error if in SubType:
s.item // error; private in SuperType
You have the definition correct and you are accessing a private field by a public accessor and mutator. What you can't do is,
s.item = 2;
which you could if item was public. Also, the fact that SubType is a sub-class of SuperType is irrelevant here. Every class can access item by it's public accessor (and mutator).
You use getter and setters methods to acces/mutate private members in a class. The getters and setters are declared as "public".
You can extend a class and inherit the parent's private members and the getters and setters to access them.
The solution or workaround is to use "Protected" access specifier that allows you to directly access/mutate the properties of a class without any getters and setter. The usage scope is only the package where the class and other classes will be. Protected doesn't require class inheritence. As long as the classes are within the same package, they can access the neighbour's protected members.
A very good explanation has been give in SO in the past - In Java, difference between default, public, protected, and private

Why can I access the private members of an enclosing class reference

I have seen many questions about accessing private members of an enclosing class. However, my question is the opposite.
If I have (as an example), the following code:
public class A {
private String outerString = "silly string";
static class B {
private final A someA = new A();
public void foo() {
String b = someA.outerString ;
}
}
}
I'm wondering why this compiles? I would have expected an error by virtue of the way in which I am accessing the 'outerString' instance variable from class A (via someA.outerString). I know that an inner class can access the enclosing class members directly by an implicit 'this' reference. But here, class B is static, so the 'this' reference won't apply.
B is a member of A and therefore has access to A's private fields and methods.
In this case, although B is static it is using an instance of A to access the field A.outerString.
static methods of a class can access private members of the same class through the same class instance. This behavior is consistent for static classes as well.
static void b(A someA) {
String b = someA.outerString;
}
1. this only works with non-static member, thats right..... But you are not using this but instance of the Outer Class.
2. And you can very well access the Outer class private member from the (Top level) inner static class.
3. Outer to Inner and from Inner to Outer has the ability to access the private member of each other..only difference is that, non static inner class has implicit reference to the Outer class, and for static inner class you must access using the Instance.

Does private variables have the same access as package/default/no modifier variables in private classes?

Does private variables have the same access as package/default/no modifier variables in private classes?
public class PublicClass {
public void test() {
InnerClass in = new InnerClass();
in.name1 = "a";
in.name2 = "b";
in.getName1();
in.getName2();
}
private class InnerClass {
private String name1;
String name2;
private String getName1() {
return name1;
}
String getName2() {
return name2;
}
}
}
The method test has access to both name1 and name2, so, what is the purpose of setting private on variables in private classes?
Update: A code example how the private keyword actually disallows access would be great.
Private members are accessible anywhere within the top-level enclosing class, i.e. PublicClass as defined in the JLS 6.6.1:
if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
So there is no way to prevent a method from accessing the private members of inner classes.
As your inner class is private, you can declare its members the way you want (including public), they will only be accessible within OuterClass.
private means/allows access inside the same (top level) class. You are using an inner class...
From the Java language specification:
A private class member or constructor is accessible only within the body of the top level class (§7.6)
http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.1
So not much use in declaring methods/fields private in inner private classes in this case indeed.
If you move the InnerClassoutside the body of the PublicClass (can have it in the same file still, though can't declare the classs private then) you will see the difference.

Why use Static Nested Classes in Java?

I am new to java and have been scratching my head understanding some its concepts.
I am following the tutorial Java tutorial. However, I cannot find the usefulness of using Static Nested Classes. I mean I think I need some good examples as to why I should want to use it. Can someone provided me some codes as examples so I can understand it better?
thax
The benefit of a static nested class over an "ordinary" class is that you can use it to reflect the relationship between two classes.
For example in the JDK there is java.util.Map and java.util.Map.Entry.
java.util.Map.Entry is declared as a public static interface and doing it this way clearly signposts its relationship to Map. It could have been defined as java.util.MapEntry but doing it as a static nested interface makes it clear that it has a strong relationship to Map.
So you'd probably only use static nested class when the nested class would only ever be used in the context of its parent.
The following example might not be for a Java beginner but one nice example of static nested class is when you want to use the Builder pattern to construct immutable objects of the outer class. The static nested class is allowed to access private members of the outer class thus constructing objects of the outer class although it has a private constructor and initializing private fields of the outer class.
E.g.
public class SomeClass {
private int someField;
private int someOtherField;
private SomeClass()
{}
public static class SomeBuilder {
private int someField;
private int someOtherField;
public SomeBuilder setSomeField(int someField)
{
this.someField = someField;
return this;
}
public SomeBuilder setSomeOtherField(int someOtherField) {
this.someOtherField = someOtherField;
return this;
}
public SomeClass build() throws ValidationException
{
validateFields();
SomeClass someClass = new SomeClass();
someClass.someField = someField;
someClass.someOtherField = someOtherField;
return someClass;
}
private void validateFields() throws ValidationException {
//Validate fields
}
}
public int getSomeField() {
return someField;
}
public int getSomeOtherField() {
return someOtherField;
}
}
Nested or inner class is just an ordinary class defined into other class. The reason to do this is typically to hide inner class from others, i.e. it is yet another level of encapsulation.
Inner class can be private, protected and public that mean exactly the same as for fields and methods.
If inner class is not private you can access it from outside too. Its name is OuterClass.InnnerClass. The nesting depth is not limited by Java specification, so inner class can have its own inner classes etc.
If inner class is not static it has yet another feature: ability to call outer's class methods and fields.
Inner class can be also anonymous. This is very useful for small callbacks, event handlers etc.
Hope this helps. Do not hesitate to ask other more concrete questions.
Another thing I should add is that if an inner class is not static, an instance of it will automatically have a reference to its parent class instance. You can reference it by using: NameOfOuterClass.this.
But if it is static, then it will not.
This, among other things, comes into play during GC (garbage collection).
Because, if an object of the inner class is not being GCed, then the outer class object it references will not be GCed either (in cases where the inner class was not static).

Categories