how to define public variable in java which cannot be modified - java

I would like every object of a class be able to access a class variable but don't want to get modified outside class.
For example the way Array.length is used.
But would also like to have a method in class which conditionally modifies this variable.
Basically this usage is for a resizing object array implementation, where length of object array can change dynamically.

There seem to be a few confusing points here.
I would like every object of a class be able to access a class variable but don't want to get modified outside class. For example the way Array.length is used.
Array.length is (effectively) a final field - an array's length in Java cannot change, so it cannot be modified from inside or outside the class.
But would also like to have a method in class which conditionally modifies this variable.
If a variable is final, as the length field in array, then its value cannot be modified at all, by anything.
You're not going to get this level of control from a field directly. Instead you should follow the standard getter pattern - make the field private and non-final, provide a public method to get its value (getLength() for example) and then set it as you need to within that class. This gives you the flexibility to change the value from within the class as you need to, while still allowing the value to be read from anywhere else.

Array.length is marked final and hence cannot be modified after the constructor is returned. I don't know what you're talking about there.
I guess, you want a private field with public getters and private setters?
private int someField = 0;
public int getSomeField() { return someField; }
private void setSomeField(int newValue) {
if (someCondition) {
someField = newValue;
}
}
Since both someField and setSomeField are private, no code outside of this class can modify the value of someField.
Code outside can only get the value of someField.
Code inside the class can conditionally set the value of someField by calling setSomeField.
Requirements met!

I think what I was trying to do could be accomplished by ArrayList implementation. Thanks for your replies.

Related

Basic about function in OOP Java

public void setTo(String to) {
this.to = to;
}
public String getTo() {
return to;
}
What does above code do? In my project file I search for setTo function and there's no setTo() found, so how does it been called? and the this refer to?
In Object Oriented programming it is wrong for other classes to have access to some variables in your program simply because as you write larger programs some of your variables can be changed without your knowledge. To stop this we make the variables in your class private and create getters and setters. The first method is a setter which can set a private variable in your class to what the user wants. This will stop many errors from occurring. The
this
is a keyword which is calling the current class you are in. If the variable passed in as a parameter is the same as the private variable declared at the top of your class, we use this to refer to the variable at the top of the class.
This two methods are the setter-getter for the property to of your class.
You source code may not call these method but still these methods are called by some framework/third party library such as JSF, Spring those you are using in your project.
Looks like you have three questions. I'll answer them in order:
What does above code do?
These methods allow code from outside the class to set and retrieve the to variable value within the class, even if it's been declared private.
In my project file I search for setTo function and there's no setTo() found, so how does it been called?
Spring uses the setter methods to do dependency injection. Basically there's Java in Spring libraries that will automatically look for these variable names and call a corresponding method named after the variable, with 'set' in front of the name.
IDEs can generate both getters and setters automatically, and since you need the setters for Spring, people tend to also have the IDE generate the getters, even if they don't plan on using them.
and the this refer to?
this is a scoping keyword.
this.to refers to a variable named to that's part of the class where these getter/setter methods are. The 'to' without the 'this.' refers to the (String to) in the parameter definition, which is the one that a call would pass in.
Essentially, "Getters" and "Setters" are methods specifically designed to interact with Fields without directly manipulating the field. This is called " FieldEncapsulation"
https://en.wikipedia.org/wiki/Field_encapsulation
Instead of directly accessing a Field, you access it's methods. You can restrict usage in your code, i.e., not allow any getting, or setting, or both.
If you have access to the Field itself, you can do anything, but if you split up methods for the field, then you are able to
better manipulate the field actions.
make your code cleaner (text.setName(name) is easier to understand than writing text = "name";
restrict access to parts of your code (depending who is using your code).
Some pieces of code also use the getters/setters specifically, and not the fields, so making sure your fields have Getters/Setters is a good practice overall.
For example, Apache BeanUtils.copyBean() will NOT copy a bean if getters/setters are not set.
You asked what
public void setTo(String to) {
this.to = to;
}
public String getTo() {
return to;
}
means so instead of saying
String setTo = "hello";
or
String setTo2 = setTo;
you can do
setTo("hello");
or
String s2 = getTo();
So setTo requires a String parameter, and then will get our "to" field String to; to whatever is the value of the parameter.
getTo will then get our field to, and return it.
There are also instances where people will add additional code into the set/get statements, but I'm not sure how common that is.
Hope this helps!
These are Getter and Setter methods for a Class global String variable (or property) named 'to'. The related Class is usually the very same Class the getter and setter methods are contained in as is the variable they are related to. If you look at the top of the Class code just under the Class constructor you should be able to locate the String variable 'to', for example:
private String to = ""; // or something similar
Usually, if there is a variable named 'to' there is also another variable named 'from' (but not always) and it to may also have getter and setter methods contained within the class.
Getter and Setter methods allow you to retrieve and modify variable data contained within a Class from another Class during run-time, for example:
MySpecialClass myClass = new MySpecialClass();
// Use the 'to' variable getter to retrieve its current
// contents and place those contents into the 'toVar' variable.
String toVar = myClass.getTo();
// Display the contents...
System.out.println(toVar);
// Set the 'to' variable within the MySpecialClass Class
// to hold the string "I hold this now"...
myClass.setTo("I hold this now");
// Use the 'to' variable getter again to retrieve its new
// contents and place those contents into the 'toVar' variable.
toVar = myClass.getTo();
// Display the contents again...
System.out.println(toVar);
Now code contained within the MySpecialClass can use the 'to' variable with its new data value. You will notice that Java Class Libraries do things this way, very much the same as setting specific properties for a JButton or JLabel etc. etc.

Accessing methods from / within difference classes, newb

I am still fairly new to java, so please bear with me.
I am having trouble understanding why it is that I can only access certain methods / functions that belong to an instance of an object from certain classes / places/. Once I create an instance of an object and then press the dot "." operator it does not bring up all the methods that I want to use for it, (I want to see all the methods that the objects class inherits and implements.)
For example:
// In a junit test class, I make an instance of the class DailyLog which takes 2
// integers
private DailyLog log; // which seems fine for now, but when I add on the next
// line:
log = new DailyLog (5,500); // It gives me an error on the semicolon on the line
// above saying "- Syntax error on token ";", , expected"
I do not understand why it will not let me create an instance of DailyLog and set it's paramaters...?
Question 2: If I just leave the first line of code in, then set the parameters of log within a method in the same class, it lets me set it's parameters, but when I press the "." operator, It does not show me the size function, which is the function I want to use. - I thought it would inherit size from a superclass, so why does it not let me use it?
Question 3: I have a method within the dailyLog class called variance, and another called numInsertions, I need to use the numInsertions method within the variance method, but when I write below, the only way I can get to the numInsertions method is through another method, and this will not work as i need to access the numInsertions method to directly to assign it's value to b, not through another method as this will change it's value.
public Integer variance() throws SimulationException{
Integer a = log.
I think it might have to do with scope, when I have another class which creates an instance of dailyLog, and when I press the ". operator on it, it gives some methods to use from the daulyLog class and it's superclass, but not all of them. I find this quite confusing, and help would be appreciated, thanks.
UPDATE**
Maybe putting more code here will help to illustrate my problem:
public class dailyLog implements Log{
private Integer userLogSize1;
private Integer maxEnt;
private ArrayList<Integer> log = new ArrayList<Integer>();
public dailyLog (Integer userLogSize, Integer maxEntry) throws SimulationException{
if ((userLogSize<= 0 || maxEntry <= 0)){
throw new SimulationException("message goes here");}
this.log = new ArrayList<Integer>(userLogSize);
for (Integer i = 0; i <= userLogSize; i++){
log.add(null);}
userLogSize1= userLogSize;
maxEnt = maxEntry;
}
public Integer numInsertions(){
Integer total = 0;
for (Integer i = 0; i < log.size(); i++){
if (log.get(i) != null){
total++;}}
return total;}
// *** below I want to write log.numentries but i cannot, why it this? I can only write
// log.get(numentries()) but that gives the wrong answer.
public Integer variance() throws SimulationException{
if (log.size() == 0){
throw new SimulationException ("Put message here");}
Integer a = log.get(0);
Integer b;
Integer d = log.get(1);
if (d == null){
b = log.get(numInsertions()-1);}
else {b = log.get(numInsertions()-2);}
Integer c = log.get(userLogSize1-1);
if ( c == null){
return a - b;}
return a-c;}
}
I think you are seeing the different protection levels in Java. For the members and methods of a class, there are generally four protection levels: private, public, protected, package-private. If a method or object is not prefixed with one the keywords private, public, protected, then it is by default package-private.
A method or class member which is private can only be referenced within the same class in which it is declared.
A method or class member which is public can only be referenced from any class in any package.
A method or class member which is protected can only be referenced from the same class and subclasses.
A method or class member which is package-private can only be referenced from within the same package. If you are developing with the default package (that is, you have not declared a package), then your code will generally treat package-private exactly as it would treat public, since all classes are defaulted to the default package.
Here is a reference and here is another question which explains the same ideas in less words.
if you're trying to pass a method from one class to the other, and you don't want to make it static, meaning it would be shared across all instances, you can create a new instance of the class in a different class. For example say you have class A and class B:
public class A {
private int a;
private void setA(int a) {
this.a = d;
and class B:
public class B {
private int b;
private void setB(int b) {
this.b = b;
so then I can call all of class A's methods by invoking a constructor from it:
public class B {
///Constructor line
private A a = new A();
A.setA(10);
System.out.println(A.a); ///should print 10
You need to understand modifiers (i.e. private, public, protected, and package-level). Every field of a class and method of a class (both static and non-static) has a modifier. If you don't specify one, then it is "package-level". You don't specify modifiers inside a code block (e.g. a method body) because it is assumed that the scope of such variables is the inside block. Just a quick example of a block-scope, the following is legal in Java:
public int foo(){
{
int max = 0;
for(int i = 0; i < 10; ++i)
if(i > max)
max = i;
}
final int max = -10;
return max;
}
In a nutshell you have the following (note that constructors would be considered methods in the following):
public: Anything can access this method or field. For fields, this means any class can set this field unless it's declared final. You should be very aware though that even an object declared final can be modified (such as an array or any other mutable object). For methods, this simply means any class can call this method.
private: Only this class can access this field or method. This means that the only place you can modify these fields or call these methods is within this class file. An instance of this class can access fields from another instance of this class (through some method written inside this class's body that references some other object instance of this class).
protected: Any class that is either in the same package as this class or a subclass of this class (could be in a separate package) has direct access to a protected field or method.
package-level: To specify package-level access, you do not specify any modifier at all (i.e. public, private, or protected...nothing). In this case, any class within this package has access to this field or method.
The better question is when should you use which? Most methods should be public and most fields should be private as a general rule. You should be very weary of people who claim that these things are for "security". The only way to ensure data integrity of an object is to only return primitive values or immutable objects or copies of mutable objects. As a quick example, let's say you implement an ArrayList (a dynamic array). Internally, you probably have an array object such as private int[] arr. If you return this array object in any public method then you run the risk of the calling class modifying the internal array and making your ArrayList inconsistent.
I would follow these guidelines:
Fields
public: Only declare a field public if it is also final and an immutable object or primitive. This should be used for persistent objects who's field never changes (i.e. once it's set in the constructor this public final field will never be changed).
protected: This should primarily be used in abstract classes. That is the abstract class declared a data structure which its subclasses can use and reference (and modify). If this is something like a list it may still be appropriate to declare it final (that is something the sub-class can modify, but not reassign).
package-level: This should primarily be used by auxiliary classes in a package. They generally shouldn't be final (although if they are things like a list that may be appropriate). As a quick example. If you implement a heap, you may want the heap nodes to hold information about what element they are storing and where they are in they heap's array. The heap is really responsible for setting this, so by declaring it package level, your heap implementation can directly access and reassign things like the heap index and heap value for each of its heap nodes.
private: Private fields are most common. Most fields should be private. This means that only methods in this class file can modify or reassign this field. This should be used when you want to guarantee the behavior of a class. If you use any other modifiers, then the behavior of this class's data may be dictated by other classes.
As for methods, it's pretty simple. A public method should be something that any class can call to query the object without disrupting the data integrity of the object (i.e. the method should not be capable of putting the object into an inconsistent state which means public methods should not, in general, return mutable fields). Private, protected, and package-level methods should all be helper methods which are used to improve modularity. Basically it depends on "who" you trust. If the method is private then you only trust this class to call it correctly. If it's package level, then you only trust classes in this package to call the method correctly. And finally if it's protected, then you only trust classes in this package and sub-classes to call this method correctly.

Changing Variable value from another class

I have an integer(levelstatus) in class A(LevelSelectScene) and I want to change it in class B(GameScene), is it possible?
here is my code:
(Code in GameScene)
public class levelComplete()
{
levelSelectScene.getInstance.levelstatus=1;
}
LevelSelectScene has an public integer levelstatus.
and after an event happens, levelComplete will trigger and will change the value of levelstatus from null to 1.
Yes.
Make your levelstatus variable as static.
Because I guess you need to change that variable in each level class.
That means,you are wanting to access that variable through out the whole Game(All levels).
And also,Declare that variable in a Util class(proposing a name LevelUtil),Since it wont attach to a single level.
It is possible to change the value any where in the project(that is in any class) since the variable is declared as public levelstatus.
If you want to change the value of the variable in many places and the new value should be the modification of previously changed value, the you should declare the variable as public static levelstatus.
I believe it is more appropriate if you look into SharedPrefences of the Android API.
Check it here.
It could be used across the whole project of yours and it is handy in those kind of cases.
You can access your variable as a public static.
Definition:
public static Boolean isPremium;
Access (do not forget import) :
your_class.isPremium

using a variable in two different java classes

I was wondering if it's possible to use a variable of a java class in another java class.Suppose variable Time is defined and calculated in Class A, how can I use it in Class B?
Other answers have suggested increasing a variable's visibility. Don't do this. It breaks encapsulation: the fact that your class uses a field to store a particular piece of information is an implementation detail; you should expose relevant information via the class's API (its methods) instead. You should make fields private in almost all cases.
Likewise, some other answers have suggested possibly making the variable static. Don't do this arbitrarily. You need to understand what static really means: it's saying that this piece of information is related to the type rather than to any one particular instance of the type. Occasionally that's appropriate, but it's generally a road towards less testable code - and in many cases it's clearly wrong. For example, a Person class may well have a name variable, but that certainly shouldn't be static - it's clearly a piece of information about a single person.
You should think carefully before exposing information anyway - consider whether there's a wider operation which the class in question could expose, instead of just giving away its data piecemeal - but when you do want to expose a field's value, use a property. For example:
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
By exposing it via a method, you can later change the implementation details without breaking existing clients.
Then from another class, you'd just call the getName() method:
// However you end up getting a reference to an instance of Person
Person person = ...;
String name = person.getName();
If you do have a static field, you can expose the value in the same way, but with a static method, which you'd call using the class name.
Be careful about returning values which are mutable, e.g. java.util.Date. This is another reason for using a getter method instead of allowing direct access to the field - you can make the method return a defensive copy where you need to.
If it is declared as public, you may use ClassA.yourVariable. On the other hand, for private access modifier, include the getter to your ClassA. On the ClassB, call ClassA.getYourVariable().
Also read about access specifiers in Java it might help.
If the variable is static, you can refer to it as A.Time from any code that has access to the variable. There's only one Time value for all of class A. If it is an instance variable, and you have an instance a of class A, you can refer to the variable as a.Time. There's a separate value for each instance of class A.
This is subject to Java's access rules:
if the field is public, any code can access it (this makes public variables kind of dangerous unless they are also declared final)
if the field is protected, only code in the same package or in a subclass of A can access it
if the field has default access, only code in the same package as class A can access it
if the field is private, only code in class A (including inner classes of A) can access it.
Alternatively, you can provide an accessor method in class A:
public class A {
. . .
public class getTime() {
return this.Time; // the "this." is optional
}
}
If you declare your Variable as public or static you will be able to access it from another class.
WHICH IS A VERY VERY BAD IDEA :)

What is the difference between field, variable, attribute, and property in Java POJOs?

When referring to internal private variables of Java POJOs that have getters/setters, I've used the following terms:
field
variable
attribute
property
Is there any difference between the above? If so, what is the correct term to use? Is there a different term to use when this entity is persisted?
From here: http://docs.oracle.com/javase/tutorial/information/glossary.html
field
A data member of a class. Unless specified otherwise, a field is not static.
property
Characteristics of an object that users can set, such as the color of a window.
attribute
Not listed in the above glossary
variable
An item of data named by an identifier. Each variable has a type, such as int or Object, and a scope. See also class variable, instance variable, local variable.
Yes, there is.
Variable can be local, field, or constant (although this is technically wrong). It's vague like attribute. Also, you should know that some people like to call final non-static (local or instance) variables
"Values". This probably comes from emerging JVM FP languages like Scala.
Field is generally a private variable on an instance class. It does not mean there is a getter and a setter.
Attribute is a vague term. It can easily be confused with XML or Java Naming API. Try to avoid using that term.
Property is the getter and setter combination.
Some examples below
public class Variables {
//Constant
public final static String MY_VARIABLE = "that was a lot for a constant";
//Value
final String dontChangeMeBro = "my god that is still long for a val";
//Field
protected String flipMe = "wee!!!";
//Property
private String ifYouThoughtTheConstantWasVerboseHaHa;
//Still the property
public String getIfYouThoughtTheConstantWasVerboseHaHa() {
return ifYouThoughtTheConstantWasVerboseHaHa;
}
//And now the setter
public void setIfYouThoughtTheConstantWasVerboseHaHa(String ifYouThoughtTheConstantWasVerboseHaHa) {
this.ifYouThoughtTheConstantWasVerboseHaHa = ifYouThoughtTheConstantWasVerboseHaHa;
}
}
There are many more combinations, but my fingers are getting tired :)
If your question was prompted by using JAXB and wanting to choose the correct XMLAccessType, I had the same question. The JAXB Javadoc says that a "field" is a non-static, non-transient instance variable. A "property" has a getter/setter pair (so it should be a private variable). A "public member" is public, and therefore is probably a constant. Also in JAXB, an "attribute" refers to part of an XML element, as in <myElement myAttribute="first">hello world</myElement>.
It seems that a Java "property," in general, can be defined as a field with at least a getter or some other public method that allows you to get its value. Some people also say that a property needs to have a setter. For definitions like this, context is everything.
Dietel and Dietel have a nice way of explaining fields vs variables.
“Together a class’s static variables and instance variables are known as its fields.” (Section 6.3)
“Variables should be declared as fields only if they’re required for use in more than one method of the class or if the program should save their values between calls to the class’s methods.” (Section 6.4)
So a class's fields are its static or instance variables - i.e. declared with class scope.
Reference - Dietel P., Dietel, H. - Java™ How To Program (Early Objects), Tenth Edition (2014)
If you take clue from Hibernate:
Hibernate reads/writes Object's state with its field.
Hibernate also maps the Java Bean style properties to DB Schema.
Hibernate Access the fields for loading/saving the object.
If the mapping is done by property, hibernate uses the getter and setter.
It is the Encapsulation that differentiates means where you have getter/setters for a field and it is called property, withthat and we hide the underlying data structure of that property within setMethod, we can prevent unwanted change inside setters. All what encapsulation stands for...
Fields must be declared and initialized before they are used. Mostly for class internal use.
Properties can be changed by setter and they are exposed by getters. Here field price has getter/setters so it is property.
class Car{
private double price;
public double getPrice() {…};
private void setPrice(double newPrice) {…};
}
<class name="Car" …>
<property name="price" column="PRICE"/>
</class>
Similarly using fields, [In hibernate it is the recommended way to MAP using fields, where private int id; is annotated #Id, but with Property you have more control]
class Car{
private double price;
}
<class name="Car">
<property name=" price" column="PRICE" access="field"/>
</class>
Java doc says:
Field is a data member of a class. A field is non static, non-transient instance variable.
Field is generally a private variable on an instance class.
The difference between a variable, field, attribute, and property in Java:
A variable is the name given to a memory location. It is the basic unit of storage in a program.
A field is a data member of a class. Unless specified otherwise, a field can be public, static, not static and final.
An attribute is another term for a field. It’s typically a public field that can be accessed directly.
In NetBeans or Eclipse, when we type object of a class and after that dot(.) they give some suggestion which are called Attributes.
A property is a term used for fields, but it typically has getter and setter combination.
Variables are comprised of fields and non-fields.
Fields can be either:
Static fields or
non-static fields also called instantiations e.g. x = F()
Non-fields can be either:
local variables, the analog of fields but inside a methods rather than outside all of them, or
parameters e.g. y in x = f(y)
In conclusion, the key distinction between variables is whether they are fields or non-fields, meaning whether they are inside a methods or outside all methods.
Basic Example (excuse me for my syntax, I am just a beginner)
Class {
//fields
method1 {
//non-fields
}
}
Actually these two terms are often used to represent same thing, but there are some exceptional situations. A field can store the state of an object. Also all fields are variables. So it is clear that there can be variables which are not fields. So looking into the 4 type of variables (class variable, instance variable, local variable and parameter variable) we can see that class variables and instance variables can affect the state of an object. In other words if a class or instance variable changes,the state of object changes. So we can say that class variables and instance variables are fields while local variables and parameter variables are not.
If you want to understand more deeply, you can head over to the source below:-
http://sajupauledayan.com/java/fields-vs-variables-in-java
Java variable, field, property
variable - named storage address. Every variable has a type which defines a memory size, attributes and behaviours. There are for types of Java variables: class variable, instance variable, local variable, method parameter
//pattern
<Java_type> <name> ;
//for example
int myInt;
String myString;
CustomClass myCustomClass;
field - member variable or data member. It is a variable inside a class(class variable or instance variable)
attribute - in some articles you can find that attribute it is an object representation of class variable. Object operates by attributes which define a set of characteristics.
CustomClass myCustomClass = new CustomClass();
myCustomClass.myAttribute = "poor fantasy"; //`myAttribute` is an attribute of `myCustomClass` object with a "poor fantasy" value
[Objective-C attributes]
property - field + bounded getter/setter. It has a field syntax but uses methods under the hood. Java does not support it in pure form. Take a look at Objective-C, Swift, Kotlin
For example Kotlin sample:
//field - Backing Field
class Person {
var name: String = "default name"
get() = field
set(value) { field = value }
}
//using
val person = Person()
person.name = "Alex" // setter is used
println(person.name) // getter is used
[Swift variable, property...]
The question is old but another important difference between a variable and a field is that a field gets a default value when it's declared.A variable, on the other hand, must be initialized.
My understanding is as below, and I am not saying that this is 100% correct, I might as well be mistaken..
A variable is something that you declare, which can by default change and have different values, but that can also be explicitly said to be final. In Java that would be:
public class Variables {
List<Object> listVariable; // declared but not assigned
final int aFinalVariableExample = 5; // declared, assigned and said to be final!
Integer foo(List<Object> someOtherObjectListVariable) {
// declare..
Object iAmAlsoAVariable;
// assign a value..
iAmAlsoAVariable = 5;
// change its value..
iAmAlsoAVariable = 8;
someOtherObjectListVariable.add(iAmAlsoAVariable);
return new Integer();
}
}
So basically, a variable is anything that is declared and can hold values. Method foo above returns a variable for example.. It returns a variable of type Integer which holds the memory address of the new Integer(); Everything else you see above are also variables, listVariable, aFinalVariableExample and explained here:
A field is a variable where scope is more clear (or concrete). The variable returning from method foo 's scope is not clear in the example above, so I would not call it a field. On the other hand, iAmAlsoVariable is a "local" field, limited by the scope of the method foo, and listVariable is an "instance" field where the scope of the field (variable) is limited by the objects scope.
A property is a field that can be accessed / mutated. Any field that exposes a getter / setter is a property.
I do not know about attribute and I would also like to repeat that this is my understanding of what variables, fields and properties are.

Categories

Resources