This question already has answers here:
When to use static methods
(24 answers)
When to use static variables/methods and when to use instance variables/methods in Java? [closed]
(5 answers)
Java Static vs Instance
(9 answers)
How and where to use Static modifier in Java?
(7 answers)
Closed 2 years ago.
I don't know when to use a static/non-static variable in a program.
package slides;
public class Person {
String name;
int age;
boolean isStaff;
public Person(String name, int age, boolean isStaff) {
// TODO Auto-generated constructor stub
this.name = name;
this.age = age;
this.isStaff = isStaff;
System.out.println(this);
}
/*
public static boolean Staf () {
return isStaff;
}
*/
}
I understand the difference between the non-static/static variable but I just don't know when to use each. So in the above code, why the function Staf can not be static? (and when it should be static?)
According to the last question, you do not understand the difference. Every non-static method implicitly receives this (as an argument). Static methods are not bound to some instances, so you just can not reference non-static fields. Static stuff can reference only static stuff.
static could be used:
For Singleton pattern, for example;
Or if you want to utilize class as simple namespace;
Or just do not like OOP and going to use COP)
The static method Staf() is not allowed to return class instance variables because Staf() can be invoked without the class Person instance being created. Therefore, Staf() can only return static variables.
You can not access non-static (instance) variables unless you do so with a) a reference to an instance (myPerson.isStaff, which would violate encapsulation) or b) from within a non-static (instance) method.
As to when you should use static, there are many discussions and diatribes on this very website which can easily be found.
Related
This question already has answers here:
how to copy SubClass object in BaseClass copy constructor
(3 answers)
Java: How to copy an object so it will be from the same subclass?
(4 answers)
Closed 4 years ago.
I have a subclass called CDAccount that has its own variables that aren't defined in the super class.
private Calendar maturityDate;
private int termOfCD;
The subclass also has a copy constructor that takes in a superclass object.
public CDAccount(Account cd){
super(cd);
}
This constructor is called by this line of code that's in a different class.
if (accounts.get(index).getType().equals("CD")) {
return new CDAccount(accounts.get(index));
}
I'm looking for a way to set the subclass variables in the copy constructor. I thought I would be able to do it with the object it takes in, because I created the object as a subclass object before setting it into the array of superclass objects.
Casting should do the trick for you:
public CDAccount(Account cd) {
super(cd);
if(cd instanceof CDAccount) {
this.maturityDate = ((CDAccount)cd).maturityDate;
this.termOfCD=((CDAccount)cd).termOfCD;
}
else {
this.maturityDate = null;
this.termOfCD= null;
}
}
This works because of the way encapsulation is implemented in Java: private variables are accessible to other instances of the same class.
The best practice would be overloading the constructor like this.
public CDAccount(CDAccount cd){
super(cd);
this.maturityDate = cd.getMaturityDate()
this.termOfCD = cd.getTermOfCD()
}
public CDAccount(Account cd){
super(cd);
}
This works for me on Java JDK v10.1
This question already has answers here:
How do I access private methods and private data members via reflection?
(6 answers)
What does it mean for a method to be public/private/other in java? [closed]
(6 answers)
Closed 8 years ago.
This program ran fine when test() method was public but as soon as I changed its modifier to private it showed Run time error.Can anybody explain why?
package ObjectClass;
import java.lang.reflect.Method;
public class reflect8 {
public static void main(String[] args) throws Exception {
Class c1 = Class.forName("ObjectClass.Reflect8A");
Object obj = c1.newInstance();
Method m1 = c1.getDeclaredMethod("test");
m1.invoke(obj);
}
}
class Reflect8A {
private void test() {
System.out.println("from test...");
}
}
Here is why you need to call setAccessible(true) even if getDeclaredMethod returns the private method.
Javadoc of getDeclaredMethod (emphasis mine):
Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.
Javadoc of invoke:
Throws IllegalAccessException - if this Method object is enforcing Java language access control and the underlying method is inaccessible.
Javadoc of setAccessible (emphasis mine):
Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used.
Method m1 = c1.getDeclaredMethod("test");
m1.setAccessible(true);
m1.invoke(obj);
This question already has answers here:
Why can I access a private variable from main method?
(7 answers)
Closed 8 years ago.
I recently see a question that what is the execution result of this code below.
public class Sandys {
private int court;
public static void main(String argv[]){
Sandys s = new Sandys(99);
System.out.println(s.court);
}
Sandys(int ballcount){
court = ballcount;
}
}
I think it can't be executed because in main i try to access a private variable.
However, this code can be perfectly executed, and the result is 99. So I am confused, why the private variable can be accessed in this code? Though the main is in Sandys class, however i create a new Sandys. Can I still access the private variable of the new Sandys object in main?
You can access private members from inside the same class, even in static methods.
main() is a special method because it is used as a starting point for java application. However, it is still a normal static method and it follows all access restrictions of static methods. Is this main() a class method? Yes, it is. Hence, it can access private members of the same class.
Consider this: if there was no access to private fields factory methods would have to be written differently.
class A {
private int a=0;
private int b=0;
private A() {}
//getters
public static A getNewInstance(int a, int b) {
A a = new A();
a.a = a;
a.b = b;
return A;
}
It does make sense, doesn't it?
You can access ALL private, protected, public and not modifier variables inside class, but you can not access private variable from another class.
P.S. It is truth also for C#, C++ and many other programming languages.
A class is defined to some particular job and in that way it may use some variables that it don't want others to access it("others" means outsider classes) and some you want other classes to access it.It all depends on your requirement.
"Private instance variables are defined to be used in only with in the class".and since in your code you are trying to access the private instance variable inside the class itself then it is perfectly legal.
Note: A static method cannot access the instance variables if u want specify the instance i mean create the instance(object) inside of the static method and access it through the created reference.
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 8 years ago.
I have a class called "setup" that has a method that returns a string
public class Setup{
public String getPW(){ return "pAssWord";}
}
I imported "Setup", tried to assign it to private static String, and then the system throws this error.
public class Something {
private Setup v_var= new Setup();
private static String password = v_var.getPW();
}
It accepts the hardcoded string, but not method called String.
Can someone explain me a logic behind this?
var_v is an instance variable. Each instance of your class would have a different value for this var. password is a static member, and is the same for all instances of your class. That's why you can't assign to it a value that is specific to an instance.
This question already has answers here:
Why are only final variables accessible in anonymous class?
(15 answers)
Closed 8 years ago.
public Destination destination(final String dest, final float price) {
return new Destination() {
private int cost;
{
cost = Math.round(price);
if (cost > 100)
System.out.prinltn("Over budget!");
}
private String label = dest;
public String readLabel() { return label; }
};
}
Parameters used by the contained anonymous inner class are modified by "final". But why?
Regarding to the rule applies to inner classes (JLS 8.1.3):
Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final.
Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.
Read more here