Hi apologies for the basic question, im sure I've been told the answer before and I've spent some time searching but couldn't find a good answer (probably because its hard to phrase as a search query), I've done a little bit of OO programming before but ive done a lot of procedural stuff recently so that seems to be clouding my thoughts.
I have a program that has to work with strings, part of that program involves sanitising a string, so I have this method:
private void sanitizeString() {
removeEscape();
removePunctuation();
removeCaps();
}
And earlier in the class declared the variable
String x = "... some string ..."
In procedural you would obviously pass all of the functions the string that they need to work on, my question is in OO is it ok to have this string declared at the top of the class and then just do something like
private void removeCaps() {
x = x.toLowerCase();
}
or should it be
private String removeCaps(String y) {
y = y.toLowerCase();
return y;
}
I think this it should be the first way, and I know that that works ok, but im doing something that has to demonstrate good OO so I just want to check I have my basic assumptions right.
Thanks
You have a trade off here:
Declaring the variable as a class variable means that you must create a new object for each String you want to sanitize.
Passing the String variable to each method means that you can reuse the same object to sanitize multiple Strings.
You must weigh the advantages and disadvantages of each approach to decide which is most appropriate for your particular situation.
Since x is declared as class variable, this one is fine:
private void removeCaps() {
x = x.toLowerCase();
}
as class variables are accessible inside class methods and you don't need to pass the class variables as arguments to same class methods
Same class variables are accessed this way only. Very simple example could be POJO classes, where you declare class variables and expose them through getter/setter methods. You don;t need to pass the class variables to these methods and some time, you can't(e.g. in getter methods).
Adding some thoughts around class variable vs. local variable in the method.
If there is a need of a variable which is theoretically associated with the class definition then the variable should be defined as class variable. e.g. employeeId, employeeName.. variables in a employee class should be defined as Employee class variables.
If there are variable needs which are local to a class method only and not required anywhere outside the method/class, then it should be defined as local variable inside the method.
If you are defining some utility methods to respond using some variables then those variables should be passed as argument to the util methods.
Back to your question:
If you are defining a entire class e.g. Sanitising, which has several methods around the string variable e.g. String class itself, then better to define your string as class variable and write the methods using the class variables.
But if you are defining Sanitising as a util/helper class then better to pass the string as method argument as normally you don;t want your util methods to be statefull (associated with the class instance).
To demonstrate good OO, you should definitly use
private String removeCaps(String y) {
return y.toLowerCase();
}
You can pass your Object, in this case your String in the global field x to the method as parameter. The String is then in the local field y and return the modified version.
Related
I would like to create a global variable in my Java program, or at least one that can be accessed by multiple methods of multiple classes. I'm fluent in C, VB6, Jovial, and many other languages, but I don't get Java. I chose it ONLY for WindowBuilder!
Here is some Java-like pseudocode for what I want, minimal to show what I am trying to do. I am aware that it doesn't compile as-is; the point I am focusing on is the NumberOfMembers variable -- how it should be declared and accessed:
public class Prelim {
public String FileName;
public int NumberOfMembers; //instantiate? I've tried all I know
//to do so! Instantiate where, all methods that use?
private void myMethod_a() {
FileName = "C:\myfilename";
ReadRoster();
//modify roster
WriteRoster();
System.out.println(NumberOfMembers);
}
}
public class ReadWriteRoster /* maybe extends Prelim?? */ {
public void ReadRoster(){
//read roster file using FileName
NumberOfMembers = 100;
}
public void WriteRoster(){
//write roster file using FileName
for (int num = 0; num < NumberOfMembers; num++){
}
//do the write`enter code here`
}
}
}
You can use "static" key Word example
static int i = 3;
With this you can access to the variable i in all class of The package and you can import this in all other package.
Java does not offer global variables in the same sense that C and some other languages do. Every variable is associated with a specific class, and often with a particular instance of that class. These two alternatives are distinguished by use of the static keyword, which indicates that the variable (or method or nested class) is associated only with its host class, not with any particular object of that class.
Probably the simplest way to achieve what you asked starts with declaring NumberOfMembers statically, like so:
public class Prelim {
// ...
public static int NumberOfMembers;
// ...
}
Then, everywhere you want to reference it in any other class, you need to qualify its name with the class to tell Java which variable of that name you mean:
// ...
Prelim.NumberOfMembers = 100;
// ...
Although it is not strictly necessary, as a matter of style I recommend using the qualified form even inside the host class.
With that said, what little I see of your code underscores your admission that you don't get Java. Classes should represent things, and to reinforce that to yourself and others, their names should be nouns or noun phrases.
You seem instead to be organizing your classes around steps in your processing algorithm. This leads to a pretty arbitrary arrangement of your code, and directly to some of the questions in code comments about instantiating class Prelim. You are trying to write procedural code, but dressing it up in object-oriented form. You can write procedural code in Java, but it is likely that your task would accommodate a bona fide object-oriented approach as well.
At first glance, an object-oriented version of your code might involve turning it inside out: it looks like it at least wants a class Roster with an instance variable numberOfMembers and methods read() and write(). Those methods could refer to the instance variable naturally, because they would be referring to a member variable of the same object. That would also better accommodate having multiple rosters in the program at the same time, each with its own number of members.
More complex example is using enum types. It is a good practice using enum as singleton.
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.
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 :)
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
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.