Can objects of a class have access to its private methods? - java

I am a beginner with respect to programming in OOPS. I was going through the concept of access modifiers in a book and got stuck at a place:
The code is as follows(I didn't care about the syntax of the code as the doubt is a conceptual one):
public class Soldier{
private int health;
public int getHealth(){
return health;
}
public void setHealth(int newHealth){
health = newHealth;
}
}
class Hospital{
private void healSoldier(Soldier soldierToHeal){
int health = soldierToHeal.getHealth();
health = health + 10;
soldierToHeal.setHealth(health);
}
public static void main(){
Soldier mySoldier = new Soldier();
mySoldier.setHealth(100);
Hospital militaryHospital = new Hospital();
mySoldier.setHealth(10); //Soldier wounded
militaryHospital.healSoldier(mySoldier);//Soldier's health increased by 10
}
}
I had a doubt in the healSoldier(Soldier soldierToHeal) method. Since this method is private, it can be accessed only within the Hospital class according to what I understood regarding the private access modifier. But we are using the same method in main to heal the soldier. Is it possible for an object of a class to have an access to its private method from main?
Thanks in advance!!

The only reason this is allowed is that your main method belongs to the body of the same class - Soldier - that also contains the body of the Hospital class. This allows it to access all private members and methods of any instance of the Hospital class.
That said, if objects of the Hospital class are going to be used by other classes, and should be allowed to call healSoldier, you should make healSoldier public. And it makes little sense for the Hospital class to be an inner class of the Soldier class. It should be a top level class.

Is it possible for an object of a class to have an access to its
private method from main?
If the object is manipulated inside a method of this class, yes.
In this case it is able as the main(String[] args) method is a method of Hospital :
class Hospital {
private void healSoldier(Soldier soldierToHeal) {
int health = soldierToHeal.getHealth();
health = health + 10;
soldierToHeal.setHealth(health);
}
public static void main(String[] args) {
Soldier mySoldier = new Soldier();
mySoldier.setHealth(100);
Hospital militaryHospital = new Hospital();
mySoldier.setHealth(10); // Soldier wounded
militaryHospital.healSoldier(mySoldier);// Soldier's health increased by 10
}
}
I didn't care about the syntax of the code as the doubt is a
conceptual one)
The syntax matters.
You probably incorrectly entered the code of the class in your actual question as the main() method seems to be defined outside of any class.

private variables and methods can be accessed anywhere from the instance of the class that declares it.
In your case the healSoldier method is called via the object of class Hospital which has declared it.

"Since this method is private, it can be accessed only within the Hospital class according to what I understood regarding the private access modifier."
This is a wrong understanding.
The right understanding is:
"..., the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top-level type that encloses the declaration of the member or constructor."
see https://docs.oracle.com/javase/specs/jls/se11/html/jls-6.html#jls-6.6.1
https://docs.oracle.com/javase/specs/jls/se17/html/jls-6.html#jls-6.6.1

Related

Why isn't my static ArrayList correctly random for each object instance? [duplicate]

To be specific, I was trying this code:
package hello;
public class Hello {
Clock clock = new Clock();
public static void main(String args[]) {
clock.sayTime();
}
}
But it gave the error
Cannot access non-static field in static method main
So I changed the declaration of clock to this:
static Clock clock = new Clock();
And it worked. What does it mean to put that keyword before the declaration? What exactly will it do and/or restrict in terms of what can be done to that object?
static members belong to the class instead of a specific instance.
It means that only one instance of a static field exists[1] even if you create a million instances of the class or you don't create any. It will be shared by all instances.
Since static methods also do not belong to a specific instance, they can't refer to instance members. In the example given, main does not know which instance of the Hello class (and therefore which instance of the Clock class) it should refer to. static members can only refer to static members. Instance members can, of course access static members.
Side note: Of course, static members can access instance members through an object reference.
Example:
public class Example {
private static boolean staticField;
private boolean instanceField;
public static void main(String[] args) {
// a static method can access static fields
staticField = true;
// a static method can access instance fields through an object reference
Example instance = new Example();
instance.instanceField = true;
}
[1]: Depending on the runtime characteristics, it can be one per ClassLoader or AppDomain or thread, but that is beside the point.
It means that there is only one instance of "clock" in Hello, not one per each separate instance of the "Hello" class, or more-so, it means that there will be one commonly shared "clock" reference among all instances of the "Hello" class.
So if you were to do a "new Hello" anywhere in your code:
A- in the first scenario (before the change, without using "static"), it would make a new clock every time a "new Hello" is called, but
B- in the second scenario (after the change, using "static"), every "new Hello" instance would still share and use the initial and same "clock" reference first created.
Unless you needed "clock" somewhere outside of main, this would work just as well:
package hello;
public class Hello
{
public static void main(String args[])
{
Clock clock=new Clock();
clock.sayTime();
}
}
The static keyword means that something (a field, method or nested class) is related to the type rather than any particular instance of the type. So for example, one calls Math.sin(...) without any instance of the Math class, and indeed you can't create an instance of the Math class.
For more information, see the relevant bit of Oracle's Java Tutorial.
Sidenote
Java unfortunately allows you to access static members as if they were instance members, e.g.
// Bad code!
Thread.currentThread().sleep(5000);
someOtherThread.sleep(5000);
That makes it look as if sleep is an instance method, but it's actually a static method - it always makes the current thread sleep. It's better practice to make this clear in the calling code:
// Clearer
Thread.sleep(5000);
The static keyword in Java means that the variable or function is shared between all instances of that class as it belongs to the type, not the actual objects themselves.
So if you have a variable: private static int i = 0; and you increment it (i++) in one instance, the change will be reflected in all instances. i will now be 1 in all instances.
Static methods can be used without instantiating an object.
Basic usage of static members...
public class Hello
{
// value / method
public static String staticValue;
public String nonStaticValue;
}
class A
{
Hello hello = new Hello();
hello.staticValue = "abc";
hello.nonStaticValue = "xyz";
}
class B
{
Hello hello2 = new Hello(); // here staticValue = "abc"
hello2.staticValue; // will have value of "abc"
hello2.nonStaticValue; // will have value of null
}
That's how you can have values shared in all class members without sending class instance Hello to other class. And whit static you don't need to create class instance.
Hello hello = new Hello();
hello.staticValue = "abc";
You can just call static values or methods by class name:
Hello.staticValue = "abc";
Static means that you don't have to create an instance of the class to use the methods or variables associated with the class. In your example, you could call:
Hello.main(new String[]()) //main(...) is declared as a static function in the Hello class
directly, instead of:
Hello h = new Hello();
h.main(new String[]()); //main(...) is a non-static function linked with the "h" variable
From inside a static method (which belongs to a class) you cannot access any members which are not static, since their values depend on your instantiation of the class. A non-static Clock object, which is an instance member, would have a different value/reference for each instance of your Hello class, and therefore you could not access it from the static portion of the class.
Static in Java:
Static is a Non Access Modifier.
The static keyword belongs to the class than instance of the class.
can be used to attach a Variable or Method to a Class.
Static keyword CAN be used with:
Method
Variable
Class nested within another Class
Initialization Block
CAN'T be used with:
Class (Not Nested)
Constructor
Interfaces
Method Local Inner Class(Difference then nested class)
Inner Class methods
Instance Variables
Local Variables
Example:
Imagine the following example which has an instance variable named count which in incremented in the constructor:
package pkg;
class StaticExample {
int count = 0;// will get memory when instance is created
StaticExample() {
count++;
System.out.println(count);
}
public static void main(String args[]) {
StaticExample c1 = new StaticExample();
StaticExample c2 = new StaticExample();
StaticExample c3 = new StaticExample();
}
}
Output:
1 1 1
Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects.
Now if we change the instance variable count to a static one then the program will produce different output:
package pkg;
class StaticExample {
static int count = 0;// will get memory when instance is created
StaticExample() {
count++;
System.out.println(count);
}
public static void main(String args[]) {
StaticExample c1 = new StaticExample();
StaticExample c2 = new StaticExample();
StaticExample c3 = new StaticExample();
}
}
Output:
1 2 3
In this case static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.
Static with Final:
The global variable which is declared as final and static remains unchanged for the whole execution. Because, Static members are stored in the class memory and they are loaded only once in the whole execution. They are common to all objects of the class. If you declare static variables as final, any of the objects can’t change their value as it is final. Therefore, variables declared as final and static are sometimes referred to as Constants. All fields of interfaces are referred as constants, because they are final and static by default.
Picture Resource : Final Static
To add to existing answers, let me try with a picture:
An interest rate of 2% is applied to ALL savings accounts. Hence it is static.
A balance should be individual, so it is not static.
This discussion has so far ignored classloader considerations. Strictly speaking, Java static fields are shared between all instances of a class for a given classloader.
A field can be assigned to either the class or an instance of a class. By default fields are instance variables. By using static the field becomes a class variable, thus there is one and only one clock. If you make a changes in one place, it's visible everywhere. Instance varables are changed independently of one another.
In Java, the static keyword can be simply regarded as indicating the following:
"without regard or relationship to any particular instance"
If you think of static in this way, it becomes easier to understand its use in the various contexts in which it is encountered:
A static field is a field that belongs to the class rather than to any particular instance
A static method is a method that has no notion of this; it is defined on the class and doesn't know about any particular instance of that class unless a reference is passed to it
A static member class is a nested class without any notion or knowledge of an instance of its enclosing class (unless a reference to an enclosing class instance is passed to it)
The keyword static is used to denote a field or a method as belonging to the class itself and not to any particular instance. Using your code, if the object Clock is static, all of the instances of the Hello class will share this Clock data member (field) in common. If you make it non-static, each individual instance of Hello will have a unique Clock.
You added a main method to your class Hello so that you could run the code. The problem with that is that the main method is static and as such, it cannot refer to non-static fields or methods inside of it. You can resolve this in two ways:
Make all fields and methods of the Hello class static so that they could be referred to inside the main method. This is not a good thing to do (or the wrong reason to make a field and/or a method static)
Create an instance of your Hello class inside the main method and access all its fields and methods the way they were intended to be accessed and used in the first place.
For you, this means the following change to your code:
package hello;
public class Hello {
private Clock clock = new Clock();
public Clock getClock() {
return clock;
}
public static void main(String args[]) {
Hello hello = new Hello();
hello.getClock().sayTime();
}
}
static methods don't use any instance variables of the class they are defined in. A very good explanation of the difference can be found on this page
I have developed a liking for static methods (only, if possible) in "helper" classes.
The calling class need not create another member (instance) variable of the helper class. You just call the methods of the helper class. Also the helper class is improved because you no longer need a constructor, and you need no member (instance) variables.
There are probably other advantages.
Static makes the clock member a class member instead of an instance member. Without the static keyword you would need to create an instance of the Hello class (which has a clock member variable) - e.g.
Hello hello = new Hello();
hello.clock.sayTime();
//Here is an example
public class StaticClass
{
static int version;
public void printVersion() {
System.out.println(version);
}
}
public class MainClass
{
public static void main(String args[]) {
StaticClass staticVar1 = new StaticClass();
staticVar1.version = 10;
staticVar1.printVersion() // Output 10
StaticClass staticVar2 = new StaticClass();
staticVar2.printVersion() // Output 10
staticVar2.version = 20;
staticVar2.printVersion() // Output 20
staticVar1.printVersion() // Output 20
}
}
Can also think of static members not having a "this" pointer. They are shared among all instances.
Understanding Static concepts
public class StaticPractise1 {
public static void main(String[] args) {
StaticPractise2 staticPractise2 = new StaticPractise2();
staticPractise2.printUddhav(); //true
StaticPractise2.printUddhav(); /* false, because printUddhav() is although inside StaticPractise2, but it is where exactly depends on PC program counter on runtime. */
StaticPractise2.printUddhavsStatic1(); //true
staticPractise2.printUddhavsStatic1(); /*false, because, when staticPractise2 is blueprinted, it tracks everything other than static things and it organizes in its own heap. So, class static methods, object can't reference */
}
}
Second Class
public class StaticPractise2 {
public static void printUddhavsStatic1() {
System.out.println("Uddhav");
}
public void printUddhav() {
System.out.println("Uddhav");
}
}
main() is a static method which has two fundamental restrictions:
The static method cannot use a non-static data member or directly call non-static method.
this() and super() cannot be used in static context.
class A {
int a = 40; //non static
public static void main(String args[]) {
System.out.println(a);
}
}
Output: Compile Time Error
A question was asked here about the choice of the word 'static' for this concept. It was dup'd to this question, but I don't think the etymology has been clearly addressed. So...
It's due to keyword reuse, starting with C.
Consider data declarations in C (inside a function body):
void f() {
int foo = 1;
static int bar = 2;
:
}
The variable foo is created on the stack when the function is entered (and destroyed when the function terminates). By contrast, bar is always there, so it's 'static' in the sense of common English - it's not going anywhere.
Java, and similar languages, have the same concept for data. Data can either be allocated per instance of the class (per object) or once for the entire class. Since Java aims to have familiar syntax for C/C++ programmers, the 'static' keyword is appropriate here.
class C {
int foo = 1;
static int bar = 2;
:
}
Lastly, we come to methods.
class C {
int foo() { ... }
static int bar() { ... }
:
}
There is, conceptually speaking, an instance of foo() for every instance of class C. There is only one instance of bar() for the entire class C. This is parallel to the case we discussed for data, and therefore using 'static' is again a sensible choice, especially if you don't want to add more reserved keywords to your language.
Static Variables Can only be accessed only in static methods, so when we declare the static variables those getter and setter methods will be static methods
static methods is a class level we can access using class name
The following is example for Static Variables Getters And Setters:
public class Static
{
private static String owner;
private static int rent;
private String car;
public String getCar() {
return car;
}
public void setCar(String car) {
this.car = car;
}
public static int getRent() {
return rent;
}
public static void setRent(int rent) {
Static.rent = rent;
}
public static String getOwner() {
return owner;
}
public static void setOwner(String owner) {
Static.owner = owner;
}
}
A member in a Java program can be declared as static using the keyword “static” preceding its declaration/definition. When a member is declared static, then it essentially means that the member is shared by all the instances of a class without making copies of per instance.
Thus static is a non-class modifier used in Java and can be applied to the following members:
Variables
Methods
Blocks
Classes (more specifically, nested classes)
When a member is declared static, then it can be accessed without using an object. This means that before a class is instantiated, the static member is active and accessible. Unlike other non-static class members that cease to exist when the object of the class goes out of scope, the static member is still obviously active.
Static Variable in Java
A member variable of a class that is declared as static is called the Static Variable. It is also called as the “Class variable”. Once the variable is declared as static, memory is allocated only once and not every time when a class is instantiated. Hence you can access the static variable without a reference to an object.
The following Java program depicts the usage of Static variables:
class Main
{
// static variables a and b
static int a = 10;
static int b;
static void printStatic()
{
a = a /2;
b = a;
System.out.println("printStatic::Value of a : "+a + " Value of b :
"+b);
}
public static void main(String[] args)
{
printStatic();
b = a*5;
a++;
System.out.println("main::Value of a : "+a + " Value of b : "+b);
}
}
output::
printStatic::Value of a : Value of b : 5
main::Value of a : 6 Value of b : 25
In the above program, we have two static variables i.e. a and b. We modify these variables in a function “printStatic” as well as in “main”. Note that the values of these static variables are preserved across the functions even when the scope of the function ends. The output shows the values of variables in two functions.
Static Method
A method in Java is static when it is preceded by the keyword “static”.
Some points that you need to remember about the static method include:
A static method belongs to the class as against other non-static
methods that are invoked using the instance of a class.
To invoke a static method, you don’t need a class object.
The static data members of the class are accessible to the static
method. The static method can even change the values of the static
data member.
A static method cannot have a reference to ‘this’ or ‘super’ members.
Even if a static method tries to refer them, it will be a compiler
error.
Just like static data, the static method can also call other static
methods. A static method cannot refer to non-static data members or
variables and cannot call non-static methods too.
The following program shows the implementation of the static method in Java:
class Main
{
// static method
static void static_method()
{
System.out.println("Static method in Java...called without any
object");
}
public static void main(String[] args)
{
static_method();
}
}
output:
Static method in Java...called without any object
Static Block In Java
Just as you have function blocks in programming languages like C++, C#, etc. in Java also, there is a special block called “static” block that usually includes a block of code related to static data.
This static block is executed at the moment when the first object of the class is created (precisely at the time of classloading) or when the static member inside the block is used.
The following program shows the usage of a static block.
class Main
{
static int sum = 0;
static int val1 = 5;
static int val2;
// static block
static {
sum = val1 + val2;
System.out.println("In static block, val1: " + val1 + " val2: "+
val2 + " sum:" + sum);
val2 = val1 * 3;
sum = val1 + val2;
}
public static void main(String[] args)
{
System.out.println("In main function, val1: " + val1 + " val2: "+ val2 + " sum:" + sum);
}
}
output:
In static block, val1: 5 val2: 0 sum:5
In main function, val1: val2: 15 sum:20
Static Class
In Java, you have static blocks, static methods, and even static variables. Hence it’s obvious that you can also have static classes. In Java, it is possible to have a class inside another class and this is called a Nested class. The class that encloses the nested class is called the Outer class.
In Java, although you can declare a nested class as Static it is not possible to have the outer class as Static.
Let’s now explore the static nested classes in Java.
Static Nested Class
As already mentioned, you can have a nested class in Java declared as static. The static nested class differs from the non-static nested class(inner class) in certain aspects as listed below.
Unlike the non-static nested class, the nested static class doesn’t need an outer class reference.
A static nested class can access only static members of the outer class as against the non-static classes that can access static as well as non-static members of the outer class.
An example of a static nested class is given below.
class Main{
private static String str = "SoftwareTestingHelp";
//Static nested class
static class NestedClass{
//non-static method
public void display() {
System.out.println("Static string in OuterClass: " + str);
}
}
public static void main(String args[])
{
Main.NestedClassobj = new Main.NestedClass();
obj.display();
}
}
output
Static string in OuterClass: SoftwareTestingHelp
I think this is how static keyword works in java.

How to access non-static variables & methods from a different class

I do not quite understand the use of "static" properly.
I have a class which includes variables that I want to access from a different class.
However, when I try to access this getter method from the different class I get an error stating:
"non-static method getAccNumber() cannot be referenced from a static context."
So, how can I find this variable's value without making it static. The problem with this is if I make it static, every instance of this object overwrites the previous value.
So they all end up with the same account number in this case.
Let me explain in more detail:
I have a Class called Account, which contains a variable called accountNumber, and a getter method called getAccNumber().
I have a second class called AccountList which is a separate arraylist class to store instances of Account. I want to create a method to remove an element based upon its accountNumber. So I'm searching and using getAccnumber() within the AccountList class to compare with a user parameter and removing if correct!
But I can't use this method without making it static!!
Any help/explanation would be greatly appreciated :)
This is what I am trying to do:
public boolean removeAccount(String AccountNumber)
{
for(int index = 0; index < accounts.size(); index++)
{
if (AccountNumber.equals(Account.getAccNumber()))
{
accounts.remove(index);
return true;
}
}
return false;
}
Thank you!
Let's take an example where you have
public class A {
static void sayHi() { System.out.println("Hi");
//Other stuff
}
and
public class B {
void sayHi() { System.out.println("Hi");
//Other stuff
}
Then
public class C {
public C() {
A.sayHi(); //Possible since function is static : no instantiation is needed.
B.sayHi(); //Impossible : you need to instantiate B class first
}
You can check out this link for a short definition:
Static Method Definition
If you declare a variable as static, it will not be unique for each instance of the class. If you declare the variable as private only, then you can create getter and setter methods that will allow you to access the variable after you have created an instance of the class. For example, if you have classA and classB and you are working in classB and want the private int size of classA:
classA a = new ClassA();
int size = a.getSize(); //getSize() returns the private int size of classA
A static variable is one that lives with the class itself. A non-static variable is unique to each instance of that class (i.e., each object built from that class.) A static variable you can access as a property of the class, like:
SomeclassIMadeUp.numberOfFish;
so if you change the numberOfFish property for that class, anywhere you reference it, you see the change (as you've noticed.)
To have one unique to each instance, don't declare the variable as static and then add a getter and/or setter method to access it.
like
private int numberOfFish;
public int getNumberOfFish() { return (numberOfFish); }
So to your question...
Ocean pacific = new Ocean();
pacific.water = Ocean.salty; // <-- Copying the value from a static variable in the class Ocean
// to the instance variable in the object pacific (which is of Ocean class).
pacific.setNumberOfFish(1000000000);
Octopus o = new Octopus();
o.diningOpportunities = pacific.getNumberOfFish(); // <-- Calls the public method to return a
// value from the instance variable in the object pacific.

Using a non-static object in a static method

Okay, I can't figure out how to work this. When the object isn't static, none of the methods or variables used work, Java just won't compile them. However, when I make the object static, the JVM returns error, throwing a popup alert and spamming the console with error messages. Here's a severely cut down version of the broken code:
public class Main {
public Hero hero = new Hero();
private static boolean newGuy;
public static void main(String[] args){
areYouNew();
if(newGuy){
createGame();
}else{
loadGame();
}
saveGame();
}
private static void createGame() {
}
private static void loadGame() {
System.out.println("Ah yes, sorry. What is your name again?");
//blah blah code here
hero.setName();
if(hero.getName().length() > 0 ){
}else{
System.out.println("Sorry? You need to type your name");
loadGame();
}
}
private static void areYouNew() {
System.out.println("Are you new?");
String newTest = sc.nextLine();
if(newTest.toLowerCase().contains("yes")){
newGuy = true;
}else if(newTest.toLowerCase().contains("no")){
newGuy = false;
}else{
System.out.println("Oops, it's a yes or no question.");
areYouNew();
}
}
}
None of the hero.whatevers work unless I set hero to static. Any way to fix this?
I already tried making the methods containing the references to hero non-static but then I can't use those methods in main()
The static part of a program is code that runs without using an instance of your Main class. When the main method is called, there is no instance of the Main class yet.
Normally, an object instance has certain fields. In your case there is only public Hero hero. Static fields, like private boolean newGuy are not part of the instance, but more like global variables. Since there is no object instance of Main yet, the hero field can't be accessed.
It is good practice to use object-oriented programming, in Java. You should probably create a new instance of your game as quickly as possible (using Main game = new Main()). Then call methods on this instance (game.createGame(), game.loadGame()). Then, you don't need to make these methods static and you can access non-static fields. Also, this would allow you to have two Main instances at the same time, each with their own hero field, if such a thing would be needed at some point in your project.
You could, of course, also make the hero field static. It's a question of code style, I suppose.

Can't access public non-static class attribute from secondary class

I have the following two classes:
public class Class1
{
public Class1 randomvariable; // Variable declared
public static void main(String[] args)
{
randomvariable = new Class1(); // Variable initialized
}
}
public class Class2
{
public static void ranMethod()
{
randomvariable.getSomething(); // I can't access the member "randomvariable" here even though it's public and it's in the same project?
}
}
I am very certain that it's a very fundamental thing I'm missing here, but what am I actually missing? The Class1 member "randomvariable" is public and so is the class and both classes are in the same project.
What do I have to do to fix this problem?
There are two problems:
Firstly, you're trying to assign a value to randomvariable from main, without there being an instance of Class1. This would be okay in an instance method, as randomvariable would be implicitly this.randomvariable - but this is a static method.
Secondly, you're trying to read the value from Class2.ranMethod, again without there being an instance of Class1 involved.
It's important that you understand what an instance variable is. It's a value associated with a particular instance of a class. So if you had a class called Person, you might have a variable called name. Now in Class2.ranMethod, you'd effectively be writing:
name.getSomething();
That makes no sense - firstly there's nothing associating this code with Person at all, and secondly it doesn't say which person is involved.
Likewise within the main method - there's no instance, so you haven't got the context.
Here's an alternative program which does work, so you can see the difference:
public class Person {
// In real code you should almost *never* have public variables
// like this. It would normally be private, and you'd expose
// a public getName() method. It might be final, too, with the value
// assigned in the constructor.
public String name;
public static void main(String[] args) {
Person x = new Person();
x.name = "Fred";
PersonPresenter.displayPerson(x);
}
}
class PersonPresenter {
// In a real system this would probably be an instance method
public static void displayPerson(Person person) {
System.out.println("I present to you: " + person.name);
}
}
As you can tell by the comments, this still isn't ideal code - but I wanted to stay fairly close to your original code.
However, this now works: main is trying to set the value of an instance variable for a particular instance, and likewise presentPerson is given a reference to an instance as a parameter, so it can find out the value of the name variable for that instance.
When you try to access randomvariable you have to specify where it lives. Since its a non-static class field, you need an instance of Class1 in order to have a randomvariable. For instance:
Class1 randomclass;
randomclass.randomvariable.getSomething();
If it were a static field instead, meaning that only one exists per class instead of one per instance, you could access it with the class name:
Class1.randomvariable.getSomething();

Why use public and private to static members and method?

I'm learning Java and I just wonder why public and private is used when a method or members is static? When static is used they are class methods and class members and could be used from other classes without creating an object, so is public and private necessary? Some help is preciated to understand. Sorry if this question is too simple for some.
The accessibility of a field or method is orthogonal to the fact that it's static or not.
You could have a static method accessible from the outside, and a static method that must only be used from inside the class itself (by other static or non-static methods). The same goes for fields.
For example:
// not visible from the outside
private static final long MILLISECONDS_IN_A_MINUTE = 1000L * 60 * 60;
public static Date addMinutes(Date d, int amount) {
return addMillis(d, MILLISECONDS_IN_A_MINUTE * amount);
}
// not visible from the outside
private static Date addMillis(Date d, long amount) {
return new Date(d.getTime() + amount);
}
It's not necessary, but there can be static methods and data members for internal use only.
An example for this is if you want an unique id for every instance of the class:
class Foo
{
private static int nextId = 0;
private static int generateId() { return ++nextId; }
private int id;
public Foo()
{
id = generateId();
}
}
As you can see, nextId and generateId() are not needed outside the class, nor should they be used outside the class. The class itself is responsible for generating id's. But you need them to be static (well, you need nextId to be static, but you can also make generateId() static since it doesn't access non-static members).
Whenever an object Foo is created, the static counter is incremented, thus you get different ids for each instance of the class. (this example is not thread-safe)
Suppose you have a static public method and this method must access to a private attribute. This private attribute must be static too. There's one reason why private static exists.
Example :
public class Test {
private static int myattr = 0;
public static void foo() {
myattr = 2;
}
}
Above, myattr must be a static attribute in order to use it in the foo() method.
Yes it is needed.
If you have a Static Method and want to use a private variables in that method, then you need to declare it static too.
Or you want the static variables not be visible to other packages, then don't declare it public.
From what I remember, it's not really needed. But public means, basically in any programming language, that it can be used by outside files. With private it can only be used within that file, and static means you cannot change the value of said reference. Whether these be functions, or variables, the same rules apply. I might be off. Haven't done Java in about a year and a half.
The ways you can incorporate these types is up to you. After all, a program is only as diverse as it's user. ^_^
Public and private keywoards have to do with visibility: which members do you want to accessible to other classes and which should be hidden or encapsulated.
Static members relate to the class as a whole, while non-static members operate on object instances.
I'm learning Java and I just wonder why public and private is used when a method or members is static?
I believe your question is due to a common misconception that the access modifiers are for instances, but they're not!
Two different instances can access each others private members if they are of the same class.
In other words, the access modifiers works on class level. Since also static members belong to some class, it makes sense to have access modifiers also on them.
A static method (or variable) that should only be used by code in the same class (as in the example by JB Nizet) should be private, while a static method or variable that may be used by code in any class should be public.
When the static is used with methods it doesn't only mean that it should be used by the members of other classes.
The case when we access the static methods of a class is one when
the class (which contains the method) cannot be instantiated i.e. no objects can be created of that class.
There may be situations when two different classes may have static methods with same name. In that case you want to use the method of the same class not the method of other class.

Categories