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.
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 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.
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.
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.
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.