Is it possible to access a private static variable and method? - java

We can access a static property of a class by writing className.propertyName, but if the property (method/variable) is private then is it possible to access that property?
For example,
class A{
static int a = 50;
}
public class HelloWorld{
public static void main(String []args){
System.out.print("A.a = ");
A obj = new A();
System.out.println(A.a);
}
}
This will print A.a = 50
But if I change static int a = 50; to private static int a = 50; then can I access that variable any how?

The private keyword means that it'll only be visible within the class. So in your example it means that you cannot access it like A.a. What you can do though is to create a public method that returns a.
private static int a = 5;
public static int getA () {
return a;
}
You can then statically call this method and retrieve the private static field.
// ...
System.out.println(A.getA());
Usually private static fields are rarely used though.
One more thing I'd like to add is the general use of static here.
As you actually create an instance of the class A the static modifier is redundant.

You cannot access the private in outside class or outside the package .Because private making them only accessible within the declared class.if you want to access the variables in the class means public,default and protected are only accessible .outside the package
means default is not possible only public and protected is possible ,protected also have different package and non sub class means not possible only sub class is possible(need to extend the class).public only accessible for all inside and outside the packages.

Related

Meaning of the Private visibility modifier

In the class 'Tosee' below, hiddenInt is visible when I call s.hiddenInt.
However, when I create a "ToSee" object in another class, 'CantSee', the private variable isn't visible. Why is this so? I was under the impression that private means that in any instance of a class, the client cant see that particular instance variable or method? Why then am I able to see hiddenInt in the main method of 'ToSee'?
public class ToSee {
private int hiddenInt = 5;
public static void main(String[] args) {
ToSee s = new ToSee();
System.out.println(s.hiddenInt);
}
}
public class CantSee {
public static void main(String[] args) {
ToSee s = new ToSee();
System.out.println(s.hiddenInt);
}
}
Private in Java means the variable or method is only accessible within the class where it is declared. If your impression about private was true, it will not be accessible anywhere ever which makes it completely useless.
A main method has special connotations in Java, yet it's still a method belonging to a particular class.
Private fields in the enclosing class are accessible to the main method, either through a local instance (in the case of instance fields) or directly (in the case of static fields).
The modifier private makes a variable or method private to the type (class) it is declared in. So only this class can see it.
You can see the variable hiddenInt in ToSee.main because ToSee.main is a static method of the TooSee class. Thus it can access all private variables of a ToSee, either static or instance variables.
Private does also NOT mean private to an instance. An instance of one class can access the private variables of another instance of the same class.
public class ToSee {
private int hiddenInt = 5;
public void printInt(ToSee toSee){
System.out.println(toSee.hiddenInt);
}
public static void main(String[] args) {
ToSee tooSee1 = new ToSee();
ToSee tooSee2 = new ToSee();
tooSee2.hiddenInt = 10;
tooSee1.printInt(tooSee2); // will output 10
}
}
I was under the impression that private means that in any instance of a class,
the client cant see that particular instance variable or method?
Incorrect! Private access modifier simply means that the variable on which it is used will be accessible only in the enclosing class. Period. Since your main() method is in ToSee class which is where you have the hiddenInt private instance variable, it is visible. Where as in case of CantSee class which is not in the ToSee class it is not visible(you need to use getter/setter methods.)
private means invisible to any code outside of the outermost enclosing class it is present in. Since the CantSee class is separate from the ToSee class it cannot see the private field. If CantSee and ToSee were both members of the same class, or one was a member of the other, then you would be able to read the private field. A few examples of structures in which the private field is readable follow :
public class Outer {
public class ToSee {
...
}
public class CantSee {
...
}
}
or
public class CantSee {
...
public class ToSee {
...
}
}

class member definition in java

I recently encountered this phrase:
"Class A has class member int a"
Probably obvious but this sentence just means a is an int defined in class A, right?
And another thing, for example a is defined under a method in class A. is it still
a class member?
I haven't found a clear definition of class member, I looked here:
but it wasn't very helpful.
Thank's in advance for the help
Class member is another way of calling static members.
class A {
int a; //instance variable
static int b; //class variable
public void c() {
int d; //local variable
}
}
In same docs
Fields that have the static modifier in their declaration are called static fields or class variables
Class variables are referenced by the class name itself, as in
Bicycle.numberOfBicycles
This makes it clear that they are class variables.
class member is not just a variable of the class. they can be accessed using the class name. That means they are static variable of that class.
The document mentioned it clearly.
public class Bicycle {
private int cadence;
private int gear;
private int speed;
// add an instance variable for the object ID
private int id;
// add a class variable for the
// number of Bicycle objects instantiated
private static int numberOfBicycles = 0;
...
}
in the above code numberOfBicycles is a class member. It can be accessed using
Bicycle.numberOfBicycles
And variables inside methods can't access like that. so they can't be class members. variables declared inside a method are local variables and belong to that method. So you can call them final, but not static or public or protected or private.
In the docs link you have mentiond, its clear in the first line (after heading) that
In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.
So it means that static keyword is used to create class fields and methods(i.e.class members).
So in your case,
class A{
int a;
public void methodA(){
int a;//inner a
}
}
What you have asked is that is int a inside methodA() still a class member?
Answer is no: since it is not preceded by static keyword.If you try to use static keyword as:
class A{
int a;
public void methodA(){
static int a;//inner a will cause compile time error
}
}
You will get compile time error.
Hope that helped!! :)
Variable in Java is a data container(memory) that stores the data values during Java program execution.There are 3 types of variables in java.
They are local variables,instance variables,static variables.
local variables - declared within the body of a method..
instance variables - declared inside the class but not inside the method,to access these variables you need to create an object
static - memory allocated only once..directly accessible and its not object specific
Static variables defined at global scope of the class and so they also refereed as class member.for example
public class TypesofVar {
int a = 10; // instance variables
static int c = 30; // static variables
public static void main(String[] args) {
int b = 20; // local variable
System.out.println(c);
System.out.println(b);
TypesofVar obj = new TypesofVar();
System.out.println(obj.a);
}
}
What you have asked is that is int a inside methodA() still a class member?
NO because it is not preceded by static keyword

How to create a class which is not inheritable and static in java?

Can you please help me how to create a class which is not inheritable and should be static in behavior (Means we should not be able to create instance of it). I need this class to store constant values. Thanks.
public final class MyClass {
private MyClass() { }
}
The final keyword makes it not inheritable, and making the constructor(s) private will help stopping it from being instantiated.
you can use final keyword to class can not be inherited.
But I would recommend you to Use Enums. Enums can not be inherited and only one instance exists per constant value. Also you can do lot more with enums.
public enum DaysOfweek
{
SUNDAY,MONDAY.....
}
You can read more about Enums here Enum Types
Why not use an interface which has a couple of static and final variables?
For the first case, you can use final class as they can't be inherited..
For your second case, you can use interface, they are very well used to store Constants.
But you cannot have both of them together (As having an interface which cannot be implemented does not make sense)..
So, the best is you can mix the property of both in one class.. You can have a final class with public static final variables, as this is what makes a variable constant in interface, will serve the purpose of constants..
public final class A {
public static final int YOUR_CONST = 5;
}
If you don't want to make instance of this class, you can have a private 0-arg constructor in it..
public final class A {
public static final int YOUR_CONST = 5;
private A() {}
}
Declare it as final which will not allow other classes to extend it, and make its constructors private so no one else (except your own class) will be able to instantiate it:
public final class MyClass {
private MyClass() {
// Private so noone else can instantiate this
}
}
Below is an example of the class to contain a constant value:
public final class Trial // it is the FINAL
{
private static final int CONSTANT_VALUE = 666;
private Trial() // it is PRIVATE instead of PUBLIC
{
}
public static int getConstantValue()
{
return CONSTANT_VALUE;
}
}
And below is an example of how to test the above class:
public class Bully //extends Trial ////"extends" WILL NOT COMPILE
{
public static void main(String[] args)
{
//Trial trial = new Trial(); ////"new Trial()" WILL NOT COMPILE
// The only thing can be done is getting a constant value from "Trial"
int acquiredValue = Trial.getConstantValue();
System.out.println(acquiredValue);
}
}
Hope that helps :))
public final class MyClass {
public static string MY_STRING;
public static int MY_INT;
private MyClass() {}
}
final : Make a class final that means this class can not be inherite further more.
static : If all methods are static the you do not need to create instance of this class. and should be static in behavior.
Singleton pattern : If your all methods are not static and you do not want to create more than one instance then you can make constructor private and keep one variable of class object in the class. And create once if it is null, and if not null then return same instance always.
Thanks

What is the use of a private static variable in Java?

If a variable is declared as public static varName;, then I can access it from anywhere as ClassName.varName. I am also aware that static members are shared by all instances of a class and are not reallocated in each instance.
Is declaring a variable as private static varName; any different from declaring a variable private varName;?
In both cases it cannot be accessed as ClassName.varName or as ClassInstance.varName from any other class.
Does declaring the variable as static give it other special properties?
Of course it can be accessed as ClassName.var_name, but only from inside the class in which it is defined - that's because it is defined as private.
public static or private static variables are often used for constants. For example, many people don't like to "hard-code" constants in their code; they like to make a public static or private static variable with a meaningful name and use that in their code, which should make the code more readable. (You should also make such constants final).
For example:
public class Example {
private final static String JDBC_URL = "jdbc:mysql://localhost/shopdb";
private final static String JDBC_USERNAME = "username";
private final static String JDBC_PASSWORD = "password";
public static void main(String[] args) {
Connection conn = DriverManager.getConnection(JDBC_URL,
JDBC_USERNAME, JDBC_PASSWORD);
// ...
}
}
Whether you make it public or private depends on whether you want the variables to be visible outside the class or not.
Static variables have a single value for all instances of a class.
If you were to make something like:
public class Person
{
private static int numberOfEyes;
private String name;
}
and then you wanted to change your name, that is fine, my name stays the same. If, however you wanted to change it so that you had 17 eyes then everyone in the world would also have 17 eyes.
Private static variables are useful in the same way that private instance variables are useful: they store state which is accessed only by code within the same class. The accessibility (private/public/etc) and the instance/static nature of the variable are entirely orthogonal concepts.
I would avoid thinking of static variables as being shared between "all instances" of the class - that suggests there has to be at least one instance for the state to be present. No - a static variable is associated with the type itself instead of any instances of the type.
So any time you want some state which is associated with the type rather than any particular instance, and you want to keep that state private (perhaps allowing controlled access via properties, for example) it makes sense to have a private static variable.
As an aside, I would strongly recommend that the only type of variables which you make public (or even non-private) are constants - static final variables of immutable types. Everything else should be private for the sake of separating API and implementation (amongst other things).
Well you are right public static variables are used without making an instance of the class but private static variables are not. The main difference between them and where I use the private static variables is when you need to use a variable in a static function. For the static functions you can only use static variables, so you make them private to not access them from other classes. That is the only case I use private static for.
Here is an example:
Class test {
public static String name = "AA";
private static String age;
public static void setAge(String yourAge) {
//here if the age variable is not static you will get an error that you cannot access non static variables from static procedures so you have to make it static and private to not be accessed from other classes
age = yourAge;
}
}
Is declaring a variable as private static varName; any different from
declaring a variable private varName;?
Yes, both are different. And the first one is called class variable because it holds single value for that class whereas the other one is called instance variable because it can hold different value for different instances(Objects). The first one is created only once in jvm and other one is created once per instance i.e if you have 10 instances then you will have 10 different private varName; in jvm.
Does declaring the variable as static give it other special
properties?
Yes, static variables gets some different properties than normal instance variables. I've mentioned few already and let's see some here: class variables (instance variables which are declared as static) can be accessed directly by using class name like ClassName.varName. And any object of that class can access and modify its value unlike instance variables are accessed by only its respective objects. Class variables can be used in static methods.
What is the use of a private static variable in Java?
Logically, private static variable is no different from public static variable rather the first one gives you more control. IMO, you can literally replace public static variable by private static variable with help of public static getter and setter methods.
One widely used area of private static variable is in implementation of simple Singleton pattern where you will have only single instance of that class in whole world. Here static identifier plays crucial role to make that single instance is accessible by outside world(Of course public static getter method also plays main role).
public class Singleton {
private static Singleton singletonInstance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return Singleton.singletonInstance;
}
}
Well, private static variables can be used to share data across instances of that class. While you are correct that we cannot access the private static variables using constructs like ClassName.member or ClassInstance.member but the member will always be visible from methods of that class or instances of that class. So in effect instances of that class will always be able to refer to member.
What is the use of a private static class variable?
Let's say you have a library book Class. Each time you create a new Book, you want to assign it a unique id. One way is to simply start at 0 and increment the id number. But, how do all the other books know the last created id number? Simple, save it as a static variable. Do patrons need to know that the actual internal id number is for each book? No. That information is private.
public class Book {
private static int numBooks = 0;
private int id;
public String name;
Book(String name) {
id = numBooks++;
this.name = name;
}
}
This is a contrived example, but I'm sure you can easily think of cases where you'd want all class instances to have access to common information that should be kept private from everyone else. Or even if you can't, it is good programming practice to make things as private as possible. What if you accidentally made that numBooks field public, even though Book users were not supposed to do anything with it. Then someone could change the number of Books without creating a new Book.
Very sneaky!
The private keyword will allow the use for the variable access within the class and static means we can access the variable in a static method.
You may need this cause a non-static reference variable cannot be accessible in a static method.
Another perspective :
A class and its instance are two different things at the runtime. A class info is "shared" by all the instances of that class.
The non-static class variables belong to instances and the static variable belongs to class.
Just like an instance variables can be private or public, static variables can also be private or public.
Static variables are those variables which are common for all the instances of a class..if one instance changes it.. then value of static variable would be updated for all other instances
For some people this makes more sense if they see it in a couple different languages so I wrote an example in Java, and PHP on my page where I explain some of these modifiers. You might be thinking about this incorrectly.
You should look at my examples if it doesn't make sense below. Go here http://www.siteconsortium.com/h/D0000D.php
The bottom line though is that it is pretty much exactly what it says it is. It's a static member variable that is private. For example if you wanted to create a Singleton object why would you want to make the SingletonExample.instance variable public. If you did a person who was using the class could easily overwrite the value.
That's all it is.
public class SingletonExample {
private static SingletonExample instance = null;
private static int value = 0;
private SingletonExample() {
++this.value;
}
public static SingletonExample getInstance() {
if(instance!=null)
return instance;
synchronized(SingletonExample.class) {
instance = new SingletonExample();
return instance;
}
}
public void printValue() {
System.out.print( this.value );
}
public static void main(String [] args) {
SingletonExample instance = getInstance();
instance.printValue();
instance = getInstance();
instance.printValue();
}
}
I'm new to Java, but one way I use static variables, as I'm assuming many people do, is to count the number of instances of the class. e.g.:
public Class Company {
private static int numCompanies;
public static int getNumCompanies(){
return numCompanies;
}
}
Then you can sysout:
Company.getNumCompanies();
You can also get access to numCompanies from each instance of the class (which I don't completely understand), but it won't be in a "static way". I have no idea if this is best practice or not, but it makes sense to me.
In the following example, eye is changed by PersonB, while leg stays the same. This is because a private variable makes a copy of itself to the method, so that its original value stays the same; while a private static value only has one copy for all the methods to share, so editing its value will change its original value.
public class test {
private static int eye=2;
private int leg=3;
public test (int eyes, int legs){
eye = eyes;
leg=leg;
}
public test (){
}
public void print(){
System.out.println(eye);
System.out.println(leg);
}
public static void main(String[] args){
test PersonA = new test();
test PersonB = new test(14,8);
PersonA.print();
}
}
>
14
3
When in a static method you use a variable, the variable have to be static too
as an example:
private static int a=0;
public static void testMethod() {
a=1;
}
If a variable is defined as public static it can be accessed via its class name from any class.
Usually functions are defined as public static which can be accessed just by calling the implementing class name.
A very good example of it is the sleep() method in Thread class
Thread.sleep(2500);
If a variable is defined as private static it can be accessed only within that class so no class name is needed or you can still use the class name (upto you).
The difference between private var_name and private static var_name is that private static variables can be accessed only by static methods of the class while private variables can be accessed by any method of that class(except static methods)
A very good example of it is while defining database connections or constants which require declaring variable as private static .
Another common example is
private static int numberOfCars=10;
public static int returnNumber(){
return numberOfCars;
}
*)If a variable is declared as private then it is not visible outside of the class.this is called as datahiding.
*)If a variable is declared as static then the value of the variable is same for all the instances and we no need to create an object to call that variable.we can call that variable by simply
classname.variablename;
private static variable will be shared in subclass as well. If you changed in one subclass and the other subclass will get the changed value, in which case, it may not what you expect.
public class PrivateStatic {
private static int var = 10;
public void setVar(int newVal) {
var = newVal;
}
public int getVar() {
return var;
}
public static void main(String... args) {
PrivateStatic p1 = new Sub1();
System.out.println(PrivateStatic.var);
p1.setVar(200);
PrivateStatic p2 = new Sub2();
System.out.println(p2.getVar());
}
}
class Sub1 extends PrivateStatic {
}
class Sub2 extends PrivateStatic {
}
If you use private static variables in your class, Static Inner classes in your class can reach your variables. This is perfectly good for context security.
ThreadLocal variables are typically implemented as private static.
In this way, they are not bound to the class and each thread has its own reference to its own "ThreadLocal" object.
Private static fields and private static methods can useful inside public static methods. They help to reduce the too much logic inside public static methods.

how private static instance variable is accessed in main()

public class test
{
private static int a;
public static void main(string[] args)
{
modify(a);
system.out.print(a);
}
public static void modify(int a)
{
a++;
}
}
i want to know how a private static variable is accessed directly in main() method.
although static variables can be accessed directly from static methods but the variable is private and method is main().. pls explain
Yes, it is static but since it is located in the same class as main method, it can be accessed by the static methods in the class (including main)... and actually also by normal methods in the same class
It doesn't bother you that modif() can access the attribute a ? Then it's the exact same thing with the main().
The only special thing about main() is the fact that this method is used as an entry point of your application. This particularity doesn't interfer with the fact that main() is static.
By the way, your modif() method doesn't really access the static a field because it's shadowed by the parameter a.
Another thing, a++ won't do anything because you're just modifying the value of the parameter a inside a method; int is a primitive and is passed by value, so your code won't change the value of a outside of the method scope.
I think you wanted something like this :
public class test{
private static int a;
public static void main(string[] args){
modify(); //<--- No parameters needed here !
system.out.print(a);
}
public static void modify(){ //<--- No parameters needed here !
a++;
}
}
If you declare a member variable as private, this means it can only be accessed from methods in the same class. Your main() method is actually a static method in the same class, so it can access any private variables.
Since main is in the same class you can access the private variable.
A private member variable is visible to any method of that class, static or not. There are restrictions on what static methods can do but those are separate from the visibility rules.
but
public class test
{
private int a;
public static void main(string[] args)
{
system.out.print(a);
}
}
you can't access a instance variable 'a' directly in main()... it will show error bcoz it is private...... but how it accesses private static...

Categories

Resources