Use of Global variables - java

Why is it that when I read others code I frequently see extensive use of "Global variables"?
For instance in Java code:
public class SomeClass {
Button btn1;
private void someMethod() {
btn = new Button();
}
}
btn1 is declared as "global" and a "convenient" variable to be used as easy access throughout the class. But when there is no modifier on it, it defaults to default access in Java.
Could this be a security risk? Why don't people declare them with private modifier right away if they are only planning to use them in only one specific class?

It is no global variable (does such a thing even exist in Java? I guess it depends on one's definition of global). It is still a class member.
The default visibility is package-private, so the variable is not public but can be accessed by other classes in the same package.
Normally one should strive for the "best" data encapsulation but there might be uses cases where this is appropriate.

btn1 is not a global variable. it is an instance variable of the class
if no access modifier is specified, then it defaults to "package" level access i.e. btn1 is accessible to all the classes which belong to the same package as SomeClass
if SomeClass is just a data holder and immutable (no setters etc) then this is perfectly OK.
It is always better to be as much more restrictive as possible when it comes to the instance variables.

That's not a global variable. It has the default access, so it's not globally visible, and it's an instance member, which means it's scoped to an instance of SomeClass. The nearest equivalent to a global variable in Java is a public static field in a public class. Even in that case it's only global with respect to the classloader for the container class you're using - a different classloader running in the same JVM and loading the same container class would have a separate static variable.
Having said all of this, I personally disapprove of fields being anything other than private, to aid encapsulation. (That doesn't give you encapsulation on its own, of course, but it's a start.) Fields are part of the implementation of the class, which should be modifiable without affecting anyone only relying on the API of the class.

private/public does not have anything to do with security, it is to limit the scope/usage withing your code.
Nevertheless it would be good practice to call them as they should be: so if they should be private, make them private.

There is no such thing as "global" in java. There is only public, private, protected and default. Default is generally frowned upon for class variables as it breaks encapsulation.
Why don't people declare them with private modifier right away if they are only planning to use them in only one specific class?
*Because they are ignorant/don't care/naughty/out to annoy you+
*delete as appropriate
+conspiricy theorists only

If your question is
Why don't people declare them with private modifier right away
then my answer would be: Because they are lazy.

Related

Is making an instance variable private only benefits the subclasses?

I'm a beginner. I'm currently learning about OOP. From what I understand, making instance variables private means it is accessible within the class only. So you need to make set and get methods to have access into it for subclasses.
But I can directly change the private instance variable within the class it is belonged right? Then this leads me to the question.
The purpose of using private variables with a getter and/or a setting to control how and who can interact with that variable.
A private variable inside a class can only be accessed within the class. That means that anything outside of the class can not be read or write to that variable.
By providing an public getter you are giving everything the ability to read that property.
By providing an public setter you are giving everything the ability to change that property.
You can change the access modifier on the getter and setter to control who can read or change the variable. You can also completely leave out a getter or setter to make variable read-only or write-only from outside the class.
If you are unfamiliar with access modifiers, I highly recommend reading up them. The most common ones when learning are public and private. Public basically means everything can see it, and private has already been discussed.
In addition to all the above, you can add additional functionality in your getter or setter. For example, you can validate input when someone uses the setter to ensure that certain rules are maintained.
E.X: If you have a variable of type string that is post to hold a 9 digit number. With the setter, you can make sure whatever is passed in is a valid number and has a specific length. If not, you can prevent the value from going through... Usually by throwing an exception.
The benefits are wide-spread and not limited to sub-classes. Don't really think about the benefit being to a particular class or object; but, rather the benefit is giving you, the programmer, more control over how others interact with your class.

Default access modifier for a method in interface in java? [duplicate]

I just started reading a Java book and wondered; which access specifier is the default one, if none is specified?
The default visibility is known as “package-private” (though you can't use this explicitly), which means the field will be accessible from inside the same package to which the class belongs.
As mdma pointed out, it isn't true for interface members though, for which the default is "public".
See Java's Access Specifiers
The default specifier depends upon context.
For classes, and interface declarations, the default is package private. This falls between protected and private, allowing only classes in the same package access. (protected is like this, but also allowing access to subclasses outside of the package.)
class MyClass // package private
{
int field; // package private field
void calc() { // package private method
}
}
For interface members (fields and methods), the default access is public. But note that the interface declaration itself defaults to package private.
interface MyInterface // package private
{
int field1; // static final public
void method1(); // public abstract
}
If we then have the declaration
public interface MyInterface2 extends MyInterface
{
}
Classes using MyInterface2 can then see field1 and method1 from the super interface, because they are public, even though they cannot see the declaration of MyInterface itself.
If no access specifier is given, it's package-level access (there is no explicit specifier for this) for classes and class members. Interface methods are implicitly public.
The default visibility (no keyword) is package which means that it will be available to every class that is located in the same package.
Interesting side note is that protected doesn't limit visibility to the subclasses but also to the other classes in the same package
It depends on what the thing is.
Top-level types (that is, classes, enums, interfaces, and annotation types not declared inside another type) are package-private by default. (JLS §6.6.1)
In classes, all members (that means fields, methods, and nested type declarations) and constructors are package-private by default. (JLS §6.6.1)
When a class has no explicitly declared constructor, the compiler inserts a default zero-argument constructor which has the same access specifier as the class. (JLS §8.8.9) The default constructor is commonly misstated as always being public, but in rare cases that's not equivalent.
In enums, constructors are private by default. Indeed, enum contructors must be private, and it is an error to specify them as public or protected. Enum constants are always public, and do not permit any access specifier. Other members of enums are package-private by default. (JLS §8.9)
In interfaces and annotation types, all members (again, that means fields, methods, and nested type declarations) are public by default. Indeed, members of interfaces and annotation types must be public, and it is an error to specify them as private or protected. (JLS §9.3 to 9.5)
Local classes are named classes declared inside a method, constructor, or initializer block. They are scoped to the {..} block in which they are declared and do not permit any access specifier. (JLS §14.3) Using reflection, you can instantiate local classes from elsewhere, and they are package-private, although I'm not sure if that detail is in the JLS.
Anonymous classes are custom classes created with new which specify a class body directly in the expression. (JLS §15.9.5) Their syntax does not permit any access specifier. Using reflection, you can instantiate anonymous classes from elsewhere, and both they and their generated constructors are are package-private, although I'm not sure if that detail is in the JLS.
Instance and static initializer blocks do not have access specifiers at the language level (JLS §8.6 & 8.7), but static initializer blocks are implemented as a method named <clinit> (JVMS §2.9), so the method must, internally, have some access specifier. I examined classes compiled by javac and by Eclipse's compiler using a hex editor and found that both generate the method as package-private. However, you can't call <clinit>() within the language because the < and > characters are invalid in a method name, and the reflection methods are hardwired to deny its existence, so effectively its access specifier is no access. The method can only be called by the VM, during class initialization. Instance initializer blocks are not compiled as separate methods; their code is copied into each constructor, so they can't be accessed individually, even by reflection.
default is a keyword that is used as an access modifier for methods and variables.
Using this access modifier will make your class, variable, method or constructor acessible from own class or package, it will be also is set if no access modifier is present.
Access Levels
Modifier Class Package Subclass EveryWhere
public Y Y Y Y
protected Y Y Y N
default Y Y N N
private Y N N N
if you use a default in a interface you will be able to implement a method there like this exemple
public interface Computer {
default void Start() {
throw new UnsupportedOperationException("Error");
}
}
However it will only works from the 8 Java version
Official Documentation
Access Modifiers in Java
See here for more details. The default is none of private/public/protected, but a completely different access specification. It's not widely used, and I prefer to be much more specific in my access definitions.
the default access specifier is package.Classes can access the members of other classes in the same package.but outside the package it appears as private
Here is a quote about package level visibility from an interview with James Gosling, the creator of Java:
Bill Venners: Java has four access levels. The default is package. I
have always wondered if making package access default was convenient
because the three keywords that people from C++ already knew about
were private, protected, and public. Or if you had some particular
reason that you felt package access should be the default.
James Gosling: A package is generally a set of things that are kind of
written together. So generically I could have done one of two things.
One was force you always to put in a keyword that gives you the
domain. Or I could have had a default value. And then the question is,
what makes a sensible default? And I tend to go for what is the least
dangerous thing.
So public would have been a really bad thing to make the default.
Private would probably have been a bad thing to make a default, if
only because people actually don't write private methods that often.
And same thing with protected. And in looking at a bunch of code that
I had, I decided that the most common thing that was reasonably safe
was in the package. And C++ didn't have a keyword for that, because
they didn't have a notion of packages.
But I liked it rather than the friends notion, because with friends
you kind of have to enumerate who all of your friends are, and so if
you add a new class to a package, then you generally end up having to
go to all of the classes in that package and update their friends,
which I had always found to be a complete pain in the butt.
But the friends list itself causes sort of a versioning problem. And
so there was this notion of a friendly class. And the nice thing that
I was making that the default -- I'll solve the problem so what should
the keyword be?
For a while there actually was a friendly keyword. But because all the
others start with "P," it was "phriendly" with a "PH." But that was
only in there for maybe a day.
http://www.artima.com/intv/gosling2P.html
Update Java 8 usage of default keyword:
As many others have noted The default visibility (no keyword)
the field will be accessible from inside the same package to which the
class belongs.
Not to be confused with the new Java 8 feature (Default Methods) that allows an interface to provide an implementation when its labeled with the default keyword.
See: Access modifiers
There is an access modifier called "default" in JAVA, which allows direct instance creation of that entity only within that package.
Here is a useful link:
Java Access Modifiers/Specifiers
First of all let me say one thing there is no such term as "Access specifier" in java. We should call everything as "Modifiers". As we know that final, static, synchronised, volatile.... are called as modifiers, even Public, private, protected, default, abstract should also be called as modifiers . Default is such a modifiers where physical existence is not there but no modifiers is placed then it should be treated as default modifiers.
To justify this take one example:
public class Simple{  
    public static void main(String args[]){  
     System.out.println("Hello Java");  
    }  
}  
Output will be: Hello Java
Now change public to private and see what compiler error you get:
It says "Modifier private is not allowed here"
What conclusion is someone can be wrong or some tutorial can be wrong but compiler cannot be wrong.
So we can say there is no term access specifier in java everything is modifiers.

Why do we make private fields instead of package local

Is there any overhead when using default access level on class field in Java?
I mean "any", even nanoseconds on startup.
I heard JVM makes a graph of scopes for fields, that could be a possible reason for overhead.
I'm too lazy to write the private keyword. Is there any good reason to write private keyword instead of package-local? Package local seems to be local enough.
"is there any good reason to write private"?
Yes there is a good reason. You do not want your private members to be accessed.
See this site for a summary of the access modifiers and when and why you should use them,
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
private = it is not okay for them to be changed other than the mother class.
no modifier = it is okay for them to be changed by any class within the same package.
protected = same as no modifier + it is okay to be changed by a subclass
public = it is okay for them to be changed in general.
If you clicked the link above you would heed warning to their recommendation
Use the most restrictive access level that makes sense for a
particular member. Use private unless you have a good reason not to.
If you put no modifier you are effectively saying,
"I explicitly want other programmers to change these fields if their class is in the same package as mine."
You should always put private unless otherwise and by doing this you are saying,
"I do not want other programmers to change these fields."
You ask about elementary OOP knowledge
You see OOP has 4 basic principles
Inherritance
Abstraction
Polymorphism
Encapsulation -this is when private or protected keyword arrices on the scene
By these keywords you can restrict acces to certain fields of an object so they cant be "seen" from outside
And now for your question
I'm too lazy to write the private keyword. Is there any good reason to write private keyword instead of package-local?
Encapsulation helps the developer to make the code more flexible and maintainable .With well encapsulation implementation, one can change one part of the code easily without affecting the other part of the code.

public or nothing

In java, do we really have to do that in order our variable or method to be public? For example:
void aaa() {
...
}
or
public void aaa() {
...
}
If it is a must, why?
Well that's not a variable, that's a method - but yes, you have to do that to make a method public. If you don't, it has the default package access, and won't be accessible from other packages. You should judge for yourself whether any particular method you write should be accessible only within the same class (make it private) to subclasses (make it protected), to the package (leave the default; you can't state package access explicitly, unfortunately) or to everything (make it public).
(This is a slight simplification of the access modifiers, but it's a start.)
As for why this is the case - typically you should limit visibility so that your type only exposes the methods which really make sense for the concept it's trying to encapsulate. You may have many more private methods which are implementation-specific, and which the outside world shouldn't know or care about.
You can ommmit access level modifier anywhere except near main method. There it must be set to public.
Not putting a modifier is actually different than public, private, or protected.
With no modifier, only the class itself and any class in the same package can access the attribute.
Learn more here: In Java, difference between default, public, protected, and private
The two methods are different: the first has package visibility, while the second one is public.
The difference is that package-visible methods appear public only to methods inside the same package, while public methods are visible to all methods, inside and outside the package.
So the answer to your question depends on your intent: if your method is truly part of your component's interface, make it private; if it is designed for use only inside the package, keep it at the default package visibility.
In your first example, the method will be package scoped -- i.e. only things in the same package can use it. So yes, you do need to declare public fields/methods/classes as such, otherwise they will have package scope.
The default is package private.
If you want public or anything else, you must specify it.
Method can be accessed by the class itself, other classes within the same package, but not outside of the package, and not by sub-classes.
See chart at bottom:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
I think it is assuming public in Java, so it is not really required.If you start having public, protected, and private throw in the mix in a single class, it is easier to see what scope the method may have.

force private member access from same class only through method in java

I want to force future users of a class to access a private member also from future code written in that class only through an accessor method (even through junit or anything like that).
is there a way to do it in java? can someone show an example if possible?
You cannot force to do that, but you can create a method and document that enforcement in the javadoc.
private int myMember;
/**
* ATTENTION: use this method instead of setting the member directly.
*/
public void setMyMember(int value) {
this.myMember = value;
}
Also, there is an alternative solution which might work. Use ThreadLocal, like this:
private final ThreadLocal<String> member = new ThreadLocal<String>();
public void setMember(final String value) {
member.set(value);
}
The member field is final and cannot be changed. Therefore, clients will be forced to call the setter directly.
As long as the field is part of the class, anyone can access it directly. This can be a problem when we try to force all (co-)authors to go through the getters/setters because those method do some conversion, checking or bookkeeping stuff. Like incrementing internal counters.
A general solution, that comes to mind: it could be possible by using annotations. You'd have to create an annotation (and the annotation processor code) to ensure, that it is a compile time error if the field is used outside of it's getter/setter method:
#GetterSetterAccessOnly
private int value;
If you want to prevent reflection you can use a SecurityManager. If this is not an option you can get the call stack with Thread.currentThread().getStackTrace() and check the caller is from your class.
Two problems with this are; the performance won't be great. Anything you can do in the method you can do externally so the simplest work around is to copy its contents without the check. ;)
I suggest you document your reason for not allowing access this way.
Make use of inheritance to hide the field:
Do your class with all the fields and getter/setters that you need. (You may make it abstract)
Do a child class, that inherits from the previews one, and since the field isn't accessible, you force the use of the getter/setter pair.
As you are talking about the accessing in the same class, they have all the freedom to access the private member directly as well as through accessor method if that member has. So basically you cannot prevent them using the member directly in the same class.
I am afraid there is no standard way to do that. If a user has access to a class instance, although a private member is declared private, permissions can be changed at runtime and accessed anyway.
You need a classloader that enforces permissions. You can make an OSGi Bundle and enforce a control policy over the instance of your objects exported as services through interfaces. However this will tie you to an OSGi container to run your application.
Well, if they have access to your code, they can do anything they want. In the worst case, they remove your getters and setters and just put in a public field instead ;)
But of course you can motivate them to not access the variable directly with an according design:
you should check whether the others should rather implement subclasses instead of changing the class itself. Then private fields are, of course, only accessed via setters and getters.
you could move the data into a different class, and use your getters and setters to access the data in the other class. Doing this just for the sake of not having the data directly in your class is maybe a bit counter-intuitive, but since you probably have a good reason why they shouldn't access that very data, it indicates a different responsibility. So refactoring to meet the SRP is a good idea anyways.

Categories

Resources