Java working with references - java

The title a little bit disappointing but I cannot figure out how to properly formulate the question.
So, I show my problem on the code.
For example we have:
public class Test {
public Value val;
Test(Value val){
this.val = val;
}
public static void main(String[] a){
Value val = new Value(1);
Test test1 = new Test(val);
val = new Value(2);
System.out.println(test1.val.val);
}
}
How can I change my code easily to let test1 point to the new Val (that that have the value of 2). Suppose the we need to have such references(to the actual variable and not the memory) all over the program
UPD: One of the solution I found is to make a "update" method. So I could write val.update(new Val(2))
UPD: I totally agree with the setter methods. What I want is not OOP style, but in my project I need a rapid solution even if it would not be the best. I think I found one solution(it is actually bad but faster then writing setters and getters. The solution is to create a "wrapper" class(I could name it "Reference")

Normally, you want to define a setter to change any of your field values in a class.
public void setVal(Value val) {
this.val = val;
}
But, since your val field is public, you don't have to use a setter at all.
// after you've declared `val` to be a new value
test1.val = val;
Setters are the convention when dealing with JavaBeans, or with frameworks that have an expectation that a field has a corresponding getter and/or setter.

Because we are supposed to give answers, I just will repeat what we got in the comments already.
To change the value of your instance variable Value val from the outside of the class, you have to write setter methods. If you want to retrieve the value, you need getter methods.
Bad practice: You should not declare the instance variable public and directly write it. This goes against OOP principles such as encapsulation aka you do not want to know what is done in the class, you just want to know its external behavior. So declare it private.
Also check Use public getters/setters to access private variables in the same class, or access the variables directly and http://www.cs.colostate.edu/~cs161/Fall12/labs/lab2/bookgetset.html

Related

How do I call variables and methods from other classes?

I'm doing a homework assignment, and I need to create methods in one class "coinDispenser", and call them in the main class, "HW1"
I'm not sure how this works, however. This is a sample of my code in coinDispenser.java:
private int numNickles = 0;
And then calling the method later in HW1.java:
System.out.println("There are "+numNickles+" nickles in the machine.")
But I always get the error "numNickles cannot be resolved to a variable" and it wants me to create the integer in the HW1 class.
How do I call the integer from within HW1.java? Changing the integer to public int type doesn't make any difference.
Well, you definitely can't access a private member variable from one class to another. In order to access a public member in a different class, you need to either make a static variable and reference it by class, or make an instance of CoinDispenser and then reference that variable.
So, in CoinDispenser, it'd be:
public int numNickles = 0;
and in HW1, you'd have:
CoinDispenser cd = new CoinDispenser();
System.out.println("There are "+ cd.numNickles + " nickles in the machine.")
If you did a static variable you could also do:
CoinDispenser.numNickles
To call a method in another class, you have two options.
Option 1:
You can declare the method to be called as static, which means that it doesn't need to be called on an object.
NOTE: If you take this route, (which you shouldn't; it's generally bad to use static methods), you have to declare numNickles as static, meaning that there is only one instance of this field no matter how many CoinDispenser objects you create.
Example:
static void methodToCallName(any arguments it takes) {
//...do some stuff...//
}
Option 2: You can create an instance of the class using the new keyword which contains the method and call the method:
Example:
// in some method in the HW1 class (Which is a horrible class name, see java conventions)
CoinDispenser dispenser = new CoinDispenser(any parameters here);
coinDispenser.whateverYourMethodIsCalled(any arguments it takes);
The whole idea of classes in an object oriented language is to keep separate things separate. When you reference a variable defined in another class, you have to tell the program where it is.
I get the sense that you haven't really learned what it means to be object oriented, and you really should look more into it. You can't fake it; there is NO getting around object orientation. You must learn to love it. Sure, it can make simple things hard, but it will make hard things soo simple.
For the second bits of your question...
Please note that numNickles should in fact be private, contrary to what other users are saying.
Java best practices advocate encapsulation, which is basically a principle saying that other parts of your program should only be able to see what they need to and the inner workings of each class should not be exposed to other classes.
How do you achieve this? Simple; use accessor and mutator methods (getters and setters) to access and modify your fields.
// Define your field like usual...
private int numNickles = 0;
// ...and add these two methods...
public void setNumNickles(int value) {
numNickles = value;
}
public int getNumNickles() {
return numNickles;
}
This may seem like a lot of work for a variable, but many IDE's will automate the process for you, and it will save you from many frustrating bugs in the long run. Get used to it, because the rest of the Java world does it.
If numNickes is in another class you can't call it since it is scoped private.
If you want access to private scoped variables you have to write a method to return it. The convention is typically
public int getNumNickles(){
return numNickles;
}
This is by design and allows the protection of variables that you do not want to expose.
Your output would then be
System.out.println("There are "+myclass.getNumNickles()+" nickles in the machine.")
Alternatively you could make the variable public
public int numNickels;
But now it can be read from, and written to, by anyone using the class.
You are trying to access the field named numNickles from your CoinDispenser class (BTW CoinDispenser is the correct name for your java class). You can not directly access the fields and methods in your HW1 class. So, as MadProgrammer has indicated in the comment under your question, follow along as that.
In your HW1.java class have something like:
CoinDispenser cd = new CoinDispenser();
System.out.println("There are "+cd.getNumNickles()+" nickles in the machine.");
The "cd" in above line of code is your handle on the CoinDispenser class. With cd, you can access (by dotting) fields and methods from any class where you use the above lines. Further, you will still not be able to access the fields and methods in your CoinDispenser class if those fields and methods are "private".
The standard way to access a private field in another class is to use a getter method.
This would be like
private int numNickles = 0;
public int getNumNickles () {
return numNickles;
}
Also useful would be a setter method
public void setNumNickles (int numNickles) {
this.numNickles = numNickles;
}
Many IDE's (e.g. Eclipse) will automatically create these methods for you upon a click of a button.
These methods can then be called upon an instance of a CoinDispenser class.
CoinDispenser coinDispenser = new CoinDispenser ();
coinDispenser.setNumNickles (23);
System.out.println("There are "+ coinDispenser.getNumNickles() + " nickles in the machine.");
First of all, there is no variable name numNickels which cause the error to occur.
Second, to access the attribute of the class coinDispenser, you will need to create an object of that class, that is
coinDispenser a=new coinDispenser();
By doing so, you can then access public methods of the class coinDispenser. Considering that the attribute numNickles is private, you have two options, which is:
1. Change numNickles to public, then access it using
a.numNickles
2. Create a public method to get private attribute in class coinDispenser
public int getNumNickles() {return numNickles;}
and access it from HW1 using
a.getNumNickles()
Java is an Object-Oriented Programming language. This means in essence, that everything is based on the concept of objects. These objects are data structures that provide data in the form of fields and methods. Every class that you provide an implementation of, needs a form of an instance, to actually do something with it.
The following example shows that when you want to make an instance of a class, you need to make a call using newCoinDispenser(100). In this case, the constructor of the class CoinDispenser requires one argument, the amount of coins. Now to access any of the fields or methods of your newly made CoinDispenser, you need to call the method using variable.method(), so in this case coinDispenser.getCoins() to retrieve the title of our book.
public class CoinDispenser {
private int coins = 100; // Set the amount of coins
public int getCoins() {
return coins;
}
}
public class HW1 {
public static void main(String[] args) {
CoinDispenser coinDispenser = new CoinDispenser(100);
System.out.println("I have " + coinDispenser.getCoins() + " left.");
}
}
NB: We are using an extra method getCoins(), a getter, to retrieve the contents of the field coins. Read more about access level here.

What is the use of encapsulation when I'm able to change the property values with setter methods?

I try to understand a lot of times but I failed to understand this.
Encapsulation is the technique of making the fields in a class private
and providing access to the fields via public methods. If a field is
declared private, it cannot be accessed by anyone outside the class,
thereby hiding the fields within the class.
How can we change the values of fields through setter methods? How do we prevent accessing the fields directly? What is the real use of encapsulation?
Assume you have an age property.
The user can enter a value of -10, which although is a valid number, is an invalid age. A setter method could have logic which would allow you to catch such things.
Another scenario, would be to have the age field, but hide it. You could also have a Date of Birth field, and in it's setter you would have something like so:
...
private int age
private Date dob
...
public void setDateOfBirth(Date dob)
{
this.dob = dob;
age = ... //some logic to calculate the age from the Date of Birth.
}
I have also been confused like you too for a long time until I read the book Encapsulation and Inheritance in Object-Oriented Programming Language and a website that explained the importance of Encapsulation. I was actually directed from the website to the book.
People always say encapsulation is "hiding of information" therefore, maybe, making encapsulation focus on security as the main use. Yes you are hiding information in practice, but that should not be the definition as it could confuse people.
Encapsulation is simply "minimizing inter-dependencies among separately-written modules by defining strict external interfaces" (quoting from the book). That is to say that when I am building a module, I want a strict contract between my clients and me on how they can access my module. Reason being that, I can improve the inner workings without it AFFECTING my client's, life, application or whatever they are using my module for. Because their "module" does not exactly depend on the Inner workings of my module but depends on the "external interface", I made available to them.
So, if I don't provide my client with a setter and give them direct access to a variable, and I realize that I need to set some restriction on the variable before my client could use it, me changing it, could be me, changing the life of my client, or application of my client with HUGE EXPENSE. But if I provided the "strict contract" by creating a "strict external interface" i.e setter, then I can easily change my inner workings with very little or no expense to my clients.
In the setter situation (using encapsulation), if it happens that when you set a variable, and I return a message informing you that it has been assigned, now I could send a message via my "interface", informing my client of the new way my module have to be interacted with, i.e "You cannot assign negative numbers" that is if my clients try to assign negative number. But if I did not use encapsulation, and gave my client direct access to a variable and I do my changes, it could result in a crashed system. Because if the restriction I implemented, is that, you could not save negatives and my client have always been able to store negatives, my clients will have a crashed system in their hands (if that "crashed system" was a banking system, imagine what could happen).
So, encapsulation is more about reducing dependency between module, and an improvement can be made "quietly" with little or no expense to other modules interacting with it, than it is of security. Because the interacting modules depend on the "strict external interface or strict contract".
I hope this explains it properly. If not you could go the links below and read for yourself.
encapsulation matters
Encapsulation and Inheritance in Object-Oriented Programming Languages
The real use of encapsulation is also in the fact that you can do additional checks/processing on the way the values are set.
You're not exactly preventing access to the fields -- you're controlling how others can access certain fields. For example you can add validation to your setter method, or you can also update some other dependent field when the setter method of a field is called.
You can prevent write or read access to the field (e.g. by only providing a getter or setter respectively) -- but encapsulation with properties allows you to do more than just that.
If you have private fields they can't be accessed outside the class, that means basically those fields don't exist to the outside world and yes you can change their value through setter methods but using setter methods you have more flexibility/control to say who gets to change the fields and to what value can they be changed to...basically with encapsulation you get to put restrictions on how and who changes your fields.
For example you have: private double salary, you setter method could restrict that only hr staff can change the salary field it could be written as:
void setSalary(Person p,double newSalary)
{
//only HR objects have access to change salary field.
If(p instanceof HR && newSalary>=0)
//change salary.
else
S.o.p("access denied");
}
Imagine if salary was public and could be access directly any can change it however and whenever they want, this basically the significance of encapsulation
The main idea behind encapsulation is data hiding. There are several reasons why we use encapsulation in object oriented programming. Some of the identified reasons for why we encapsulation are as follows (The real use of encapsulation).
Better maintainability: When all the properties are private and encapsulated, it is easy for us to maintain the program simply by changing the methods.
Make Debugging Easy: This is in line with the above point. We know that the object can only be manipulated through methods. So, this makes it easy to debug and catch bugs.
Have a Controlled Environment: Let the users use the given objects, in a controlled manner, through objects.
Hide Complexities: Hiding the complexities irrelevant to the users. Sometimes, some properties and methods are only for internal use and the user doesn't have to know about these. This makes is simple for the user to use the object.
So, to answer the question, "What is the use of encapsulation when I'm able to change the property values with setter methods?", given above are some of the main reasons why we use encapsulation. To provide an understanding on why, getters and setters are useful, given below are some important points, obtained from this article.
You can limit the values that can be stored in a field (i.e. gender must be F or M).
You can take actions when the field is modified (trigger event, validate, etc).
You can provide thread safety by synchronizing the method.
You can switch to a new data representation (i.e. calculated fields, different data type)
Any how i am able to change the values of fields through setter methods.
Only if the setter method lets you do that.
How we are preventing the accessing fields?
The setter and getter get to control if and how you can access the fields.
A setter may check if the value is valid. It may ask a SecurityManager if you should be allowed to do this. It may convert between data types. And so on.
Lets suppose you make a custom Date class with the following setters / getters:
getDay()
getMonth()
getYear()
setDay()
setMonth()
setYear()
Internally you could store the date using:
private int day;
private int month;
private int year;
Or you could store the date using a java.lang.Date-object:
private Date date;
Encapsulation doesn't expose how your class is working internally. It gives you more freedom to change how your class works. It gives you the option to control the access to your class. You can check if what the user enters is valid (you don't want the user to enter a day with a value of 32).
It's aim is nothing but protecting anything which is prone to change. You have plenty of examples on the web, so I give you some of the advantages of it:
Encapsulated Code is more flexible and easy to change with new requirements
Allows you to control who can access what. (!!!)
Helps to write immutable class in Java
It allows you to change one part of code without affecting other part of code.
Accessing fields thru methods make difference because it makes it OOP. Eg you can extend you class and change the behaviour which you cannot do with direct access. If you have getters / setters you can make a proxy of your class and do some AOP or a make a 1.4 dynamic proxy. You can make a mock from your class and make unit testing...
Encapsultaion is used for hiding the member variables ,by making member as private and access that member variable by getter and setter methods.
Example
class Encapsulation{
private int value ;
Encapsulation() {
System.out.println("constructor calling ");
}
void setValue(int value){
this.value = value;
}
int getValue() {
return value;
}
}
class EncapsulationMain {
public static void main(String args[]) {
Encapsulation obj = new Encapsulation();
obj.setValue(4);
//System.out.print("value is "+obj.value);
//obj.value = 55;
//System.out.print("obj changing the value"+obj.value);
System.out.print("calling the value through the getterMethod"+obj.getValue());
}
}
you cannot access the private value outside the class.
Well, encapsulation is not all about hiding data. It is all about getting control over what is stored in the fields. Using encapsulation we can make a field as read-only or write-only depending upon the requirements.Also the users don't know how the data is stored in the fields. We can use some special encryption in the setter methods and store it in the fields.
For example human is a object. We only require the name field of the human to be read by the user but not to be modified. Then we define only get method on the name field.This is how the encapsulation is useful.
If you have class all of its properties are private-meaning that they cannot be accessed from outside the class- and the only way to interact with class properties is through its public methods.
You are changing tha values by giving the public access to those methods(setters).
using encapsulation the fields of a class can be made read-only or write-only.
Instead of letting everyone access the variables directly:
public Object object;
Is better to use SET and GET methods, or for example just the GET method (Sometimes you dont want nobody to set other value to that variable).
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
By using encapsulation you separate your class from the out-side world (other classes) and out-side world can access and modify your class instance variables through access modifiers, which provides several benefits:
-You can do some logging in your getter/setter methods.
-You can validate /normalize (for example trim spaces, remove special character,...) Your input in setter method.
And also you can hide your implementation from the outside world, for example you have a collection like array list in your class and you write your getter method like this
public List<t> get collection(){
return new ArrayList<t>(this.arrayList);
}
So in this case, in the future if you decide to change your implementation of collection from array list to something else like linked list, you are free to do so because out side world doesn't know anything about your implementation.
Encapsulation is not about secrecy, it is about reducing dependency over separate part of the application.
We control dependency (loose / weak / low coupling) by hiding information over separate part of the application.
Adding to Uche Dim's answer, look at the following example:
Two Connections:
public class Area {
// fields to calculate area
private int length;
private int breadth;
// constructor to initialize values
Area(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getBreadth() {
return breadth;
}
public void setBreadth(int breadth) {
this.breadth = breadth;
}
public int getArea() {
int area = length * breadth;
return area;
}
}
class Main {
public static void main(String[] args) {
Area rectangle = new Area(5, 6);
// Two Connections
int length = rectangle.getLength();
int breadth = rectangle.getBreadth();
int area = length * breadth;
System.out.println("Area: " + area);
}
}
Please note that in the Main class, we are calling two methods (getLength() and getBreadth()) of Area class.
One Connection:
public class Area {
// fields to calculate area
private int length;
private int breadth;
// constructor to initialize values
Area(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
public int getArea() {
int area = length * breadth;
return area;
}
}
class Main {
public static void main(String[] args) {
Area rectangle = new Area(5, 6);
// One Connection
int area = rectangle.getArea();
System.out.println("Area: " + area);
}
}
Here, in the Main class, we are calling one methods (getArea()) of Area class.
So in the second example, the connection is weaker than the previous one (first one calling two methods or the Area class, second one calling one method of the Area class). Given, less connection (lower / weaker coupling) is better, the second example is better.
We should always keep fields and methods private unless necessary. In the Two Connections example, we made the mistake of creating the getters unnecessarily. As we have created it, the IntelliJ Idea (auto suggestion of modern IDE) suggested the developer who was working on the Main class that you can use the getLength() and getBreadth() methods and he did. He did not inquire further to check if there was a getArea() method. As a result he created stronger coupling than necessary.
We should not unnecessarily create getters. We should not unnecessarily make fields public or protected. If you must, first try protected, if that does not work then make it public. That way we will have a lesser possibility of having a tighter coupling.
If you still have the question "what is the difference between making a field public compared to making a field private but it's getters public?", in other words "Why should we use a function to get a value instead of getting it directly?" Well it gives you another layer of abstraction. For example, if you need some extra processing of the data before receiving it (ex. validation), you can do it there. Moreover, once you expose internals of a class, you can not change that internal representation or make it better until making changes in all client codes. 
For example, suppose you did something like:
public class Area {
private int length;
private int breadth;
}
class Main {
public static void main(String[] args) {
Area rectangle = new Area(5, 6);
int area = rectangle.length * rectangle.breadth;
System.out.println("Area: " + area);
}
}
Now, if you want to change breadth to width in Area class, you can not do it without breaking the program, unless you search and replace rectangle.breadth with rectangle.width in all the clients where rectangle.breadth was used (in this case Main class).
There are other benefits as well. For example, Member variables cannot be overridden like methods. If a class has getters and setters, it's subclass can override these methods and return what makes more sense in the context of subclass.
Please check Why getter and setter are better than public fields in Java? for more details.
P.S. These are trivial examples, but in large scale, when program grows and frequent change requests are a reality, this makes sense.
I'm OK with using get and set, to mask and make reengineering easier, but if you tell to a novice programmer that using get and set does encapsulation, as I've seen many times, they will use set and get for internal members initialized by the constructor.
And this 99.9 % is wrong!!!!!
private uint8_t myvar = 0;
setMyVar(uint8_t value){
this.myvar = value * (20 / 41);
}
uint8_t getMyVar(){
return this. myvar ;
}
That’s for me is ok, but I think encapsulation is a method first, rather than get and set.
My inglish is not very well,but I think that this article says something like this.

Difference between myClassInstance.property and myClassInsance.getProperty()?

Iam a Java beginner and i would like to ask whats the pros and cons about this:
If i make a Class and i wont write my own setters and getters i can just get and set my class's properties like:
myClassInstance.name = "Jones"
myClassInstance.job = "Manager"
System.out.println(myClassInstance.name);
System.out.println(myClassInstance.job);
Why better if i make getters and setters and do like this:
myClassInstance.setName("Jones");
myClassInstance.setJob("Manager");
System.out.println(myClassInstance.getName());
System.out.println(myClassInstance.getJob());
This question is related to one of the basic principals of OO design: Encapsulation!
Accessors (also known as getters and setters) are methods that let you read and write the value of an instance variable of an object
public class AccessorExample {
private String attribute;
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
}
Why to use them?
Getter and Setters make APIs more stable. Lets consider a field public in a class which is accessed by other classes. Now later on, you want to add any extra logic while getting and setting the variable. This will impact the existing client that uses the API. So any changes to this public field will require change to each class that refers it. On the contrary, with accessor methods, one can easily add some logic like cache some data, lazily initialize it later. Moreover, one can fire a property changed event if the new value is different from the previous value. All this will be seamless to the class that gets value using accessor method.
Also Getters and setters methods allow different access levels - for eg. Get may be public, but the Set could be protected.
directly accessing the fields will lead to voilation of encapsulation.
making public variables to access them will be difficult to manage the state of that object.
where as with methods you can easily control state of the object.
Using getters and setters instead of public members is called encapsulation, and is a fundamental OOP concept. This way you are able to control the input and keep some sort of logic and validity to your models.
class Bottle {
public int volume = 0;
}
class EncapsulatedBottle {
private int volume = 0;
public void setVolume(int volume) throws Exception {
if (volume < 1) {
throw new Exception("A bottle cannot have a negative volume");
}
this.volume = volume;
}
public int getVolume() {
return this.volume;
}
}
Spot the difference :-)
Using getters and setters gives you more control over the validity of your objects, giving you the option of testing values that are set to ensure that they are reasonable, etc. (And of course, for read-only properties, you just leave off the setter.) On a modern JVM with a just-in-time compiler, they essentially don't cost anything; if they're really just reading and writing to a private data member, and if they're in a hotspot (bit of code that gets used a lot), the JIT will inline them.
Using getters/setters is normally better, because:
you can restrict (public) access to readonly (no setter)
you can add additional code without having to recompile/change the users of the property (i.e. classes that call the getter/setter)
it complies with the Java Bean specification which states a property must have getters/setters - and many libraries/frameworks, like Java EL etc. rely on that contract

Advantage of using "this."

I've read many large projects in OOP, and I notice that a lot of them use this.[variable], [ClassName].[staticVariable]. For example:
public class ABC {
private float mX;
public static float y;
public float getX() {
return this.mX;
}
public float doSomethingWithY() {
return ABC.y;
}
}
And even with Eclipse auto-generated Getters & Setters feature, it also comes with this.[variable], although it's unnecessary, because no local variable is declared there.
Is there any advantage when using these notations, or it's just a code style?
EDIT so some people don't misunderstand. I know what this and [ClassName].[staticVariable] stand for. But in this case, it's unnecessary. The question is: Even if it's unnecessary, why do guru coders still add it? When they need to update/fix a huge project, will there be any advantage and disadvantage?
Basically with this, you KNOW for sure that you are working with a class attribute, not with a variable created inside the method or maybe received as a parameter.
And also, it helps in case you have a local var with the same name.
And the final reason: readability.
It's necessary in some circumstances, for example this. is required when you need to use a member variable rather than a local method parameter of the same name.
It's also necessary for static variables where you need to be specific which class you want to get the static variable from (many classes could define static variables with the same name).
Apart from the necessary cases, it's really a matter of coding style. My recommendation is to use it whenever it helps to resolve potential ambiguity.
In complicated methods, it's sometimes nice to make a distinction between instance variables in this class, and local variables in a particular function. This distinction is immediately obvious when you use "this."
For small pieces of code it doesn't matter but sometimes this can happen:
public float getX() {
....
int mX = someFunc()
...
return mX;
}
In this case, the local value is returned instead of the member variable.
You normally want to be explicit and say this.mX. However, you shouldn't have huge functions anyway.
this.? '?' is a member variable, this is a reference to the current object.
see this
Its syntax,if you want to access instance variable of a class use the (reference of the object).(instance variable name) .Like
A a= new A();// for non static class,this for the current object
a.(instance variable name)
// for non static class do the same but use (class name).variable name

Java Variables Basics

Ok, so I am about to embarrass my self here but I am working on a project that I will need to get some help on so I need to get some conventions down so I don't look too stupid. I have only been doing java for 2 months and 100% of that has been on Android.
I need some help understanding setting up variables and why I should do it a certain way.
Here is an example of my variables list for a class:
Button listen,feed;
Context context = this;
int totalSize = 0;
int downloadedSize = 0;
SeekBar seek;
String[] feedContent = new String[1000];
String[] feedItems = new String[1000];
ListView podcast_list = null;
HtmlGrabber html = new HtmlGrabber();
String pkg = "com.TwitForAndroid";
TextView progress = null;
long cp = 0;
long tp = 0;
String source = null;
String pageContent = null;
String pageName = "http://www.shanescode.com";
DataBaseHelper mdbHelper = new DataBaseHelper(this);
int songdur = 0;
So all of these are variables that I want to use in all through the whole class. Why would I make something a static, or a final. I understand Public but why make something private?
Thanks for your help and please don't be too harsh. I just need some clarification.
These words all alter the way the variable to which they are applied can be used in code.
static means that the variable will only be created once for the entire class, rather than one for each different instance of that class.
public class MyClass{
public static int myNumber;
}
In this case the variable is accessed as MyClass.myNumber, rather than through an instance of MyClass. Static variables are used when you want to store data about the class as a whole rather than about an individual instance.
final prevents the variable's value from changing after it is set the first time. It must be given an initial value either as part of its declaration:
public final int myNumber = 3;
or as part of the class's constructor:
public MyClass(int number){
this.myNumber = 3;
Once this is done, the variable's value cannot be changed. Keep in mind, though, that if the variable is storing an object this does not prevent the object's variable from being changed. This keyword is used to keep a piece of data constant, which can make writing code using that data much easier.
private modifies the visibility of the variable. A private variable can be accessed by the instance which contains it, but not outside that:
public class MyClass{
private int myNumber;
public void changeNumber(int number){
this.myNumber = number; //this works
}
}
MyClass myInstance = new MyClass();
myInstance.myNumber = 3; //This does not work
myInstance.changeNumber(3) //This works
Visibility is used to control how a class's variables can be used by other code. This is very important when writing code which will be used by other programmers, in order to control how they can access the internal structure of your classes. Public and private are actually only two of the four possible levels of visibility in Java: the others are protected and "no (visibility) modifier" (a.k.a not public or private or protected). The differences between these four levels is detailed here.
static = same for all instances of a class.
final = unchanging (reference) for a particular instance.
If you needed some field (aka a class variable) to be shared by all instances of a class (e.g., a constant) then you might make it static.
If you know some field is immutable (at least, it's reference is immutable) in an instance, then it is good practice to make it final. Again, constants would be a good example of a field to make final; anything that is constant within an instance from construction time on is also a good candidate for final.
A search for "java final static" gives pretty useful further reference on the use of those keywords.
The use of the private keyword controls what can accessed by other classes. I'd say it's biggest use is to help developers "do the right thing" - instead of accessing the internals of the implementation of another class, which could produce all sorts of unwanted behavior, it forces using accessor/mutator methods, which the class implementor can use to enforce the appropriate constraints.
Private
The idea behind using private is information hiding. Forget about software for a second; imagine a piece of hardware, like an X-Box or something. Somewhere on it, it has a little hatch to access the inside, usually sporting a sticker: "open this up and warranty is void."
Using private is sticking a sticker like that in your software component; some things are 'inside' only, and while it would be easy for anyone to open it up and play with the inside anyways, you're letting them know that if they do, you're not responsible for the unexpected behavior that results.
Static
The static keyword does not mean "same for all instances of a class"; that's a simplification. Rather, it is the antonym of "dynamic". Using the static keyword means "There is no dynamic dispatching on this member." This means that the compiler and not the run-time determines what code executes when you call this method.
Since thee are no instances of objects at compile-time this means that a static member has no access to an instance.
An example:
public class Cat {
public static void speak() { System.out.println("meow"); }
}
public class Lion extends Cat {
public static void speak() { System.out.println("ROAR"); }
}
// ...
public static void main(String argv[]) {
Cat c = new Lion();
c.speak();
}
The above prints "meow" - not "roar" - because speak is a static member, and the declared type of c is Cat, so the compiler builds in such a way that Cat.speak is executed, not Lion.speak. Were there dynamic dispatching on static members, then Lion.speak would execute, as the run-time type of c is Lion.
Another thing that might trip you up is this:
Not everything has to be a class level variable; you should have a variable defined for the smallest scope it needs to be defined.
So as an example, suppose your class only has one method which uses your TextView progress variable. Move that declaration into the method that needs it. This way it tidies things up and helps you make more robust code by separating out things that are really separate.
I don't know why you would make anything private.
Folks will chime in and say that private is a Very Important Thing.
Some folks will claim that you can't do encapsulation without private. Most of this seems to be privacy for privacy's sake.
If you are selling your code to someone else, then you must carefully separate the interface elements of your class from the implementation details of your class. In this case, you want to make the implementation private (or protected) so that -- for legal purposes -- the code you sell doesn't expose too much of the implementation details.
Otherwise, if you're not selling it, don't waste a lot of time on private.
Invest your time in separating Interface from Implementation. Document the Interface portions carefully to be sure you're playing by the rules. Clearly and cleanly keep the implementation details separate. Consider using private as a way to have the compiler "look over your shoulder" to be sure you've really separated interface from implementation.
One of the aspects of the object oriented approach that has made it so wildly popular is that you can hide your variables inside of a class. The class becomes like a container. Now you as the programmer get to decide how you want the users of your class to interact with it. In Java, the tradition is to provide an API -- a public interface for your class using methods of the class.
To make this approach work, you declare your variables as private ( which means only methods within your class can access them ) and then provide other methods to access them. For example,
private int someNumber;
This variable can only be accessed from within your class. Do you think others might need access to it from outside of the class? You would create a method to allow access:
public int getSomeNumber()
{
return someNumber;
}
Perhaps users of your class will also need the ability to set someNumber as well. In that case, you provide a method to do that as well:
public void setSomeNumber( int someNumber )
{
this.someNumber = someNumber;
}
Why all of this work just to get access to a class member that you could just as easily declare as public? If you do it using this approach, you have control over how others access the data in your class. Imagine that you want to make sure that someNumber only gets set to be a number < 100. You can provide that check in your setSomeNumber method. By declaring your variables to have private access, you protect your class from getting used incorrectly, and make it easier on everyone who needs to use it -- including yourself!
Declaring a variable to have static access means that you do not need an instance of the class to access the variable. In Java, generally you write a class and then create an instance of it. You can have as many instances of that class as you want, and they all keep track of their own data. You can also declare variables that are part of the class itself, and this is where the static keyword comes in. If you create a variable...
static int classVariable = 0;
the variable can be accessed without a class instance. For example, you might see this done from time to time:
public static final int MY_CONSTANT = 1;
While there are better ways to do this now, it is still a common pattern. You use this variable without any instance of the class like this:
myInstance.setSomeNumber( MyClass.MY_CONSTANT );
java.awt.Color uses static variables this way. You can also declare methods to be static ( look at public static void main, the starting point for your programs ). Statics are useful, but use them sparingly because creating instances of classes can often result in better designs.
Finally ( pun intended ), why would you ever want to declare a variable to be final? If you know that the value should never change, declaring it as final means that if you write some code that tries to change that value, the compiler will start complaining. This again helps protect from making silly mistakes that can add up to really annoying bugs.
If you look at the static variable example above, the final keyword is also used. This is a time when you have decided that you want to make a variable public, but also want to protect it from being changed. You do this by making it public and final.

Categories

Resources