I'm having issues with a concept from an assignment I'm working on
public class MyHugeInteger
{
MyIntList list = new MyIntList();
public int compareTo(MyHugeInteger hugeInt)
{
if (list.size() > this.list.size()) //this is where things don't work
return (-1);
if (list.size() < this.list.size())
return (1);
}
Basically, I need to be able to use the 'list' variable from the passed version of the object to be able to compare it to the list variable from the current object.
I had a similar problem to this before, and my professor responded with "objects of the same class can access each others' private data members. So you do have access to other.size from "this" and can check Set sizes for equality."
This is what I'm trying to use in the code given, but I found an example saying that this will call the field variable, the one already called by just saying 'list'
Am I missing something?
The comment was right, hugeInt.list.size() > this.list.size() instead of using 'this' for the passed object. One of those things that you miss when you're overthinking the problem
If you're trying to use the Java framework to sort things or use the compareTo method, as intended, you need to implements Comparable<MyHugeInteger> in your class.
public class MyHugeInteger implements Comparable<MyHugeInteger>
Then, to fix the error, you need to use the parameter object because this.list and the unqualified list are the exact same object.
Also consider what happens when sizes are equal.
Tip: don't need to rewrite the integer comparison logic yourself.
#Override
public int compareTo(MyHugeInteger hugeInt) {
return Integer.compare(this.list.size(), hugeInt.list.size());
}
Multiply by negative one or flip the parameters if you notice the ordering is wrong.
Related
Say I have some class:
public class A {
private int val = 0;
public int getVal() {
return val;
}
public void addFrom(A otherA) {
this.val += otherA.val;
if (otherA.val > 0)
otherA.val = 0;
else
otherA = Math.abs(otherA.val);
}
}
Should I be using getter methods instead to use otherA's val variable? Is it better style to do so?
Edit: This is a very simplified version of a class that takes much too long to read. But assume that there IS lazy initialization going on, that there are other methods that access this class, etc. I have updated the example method so that this may be more clear, but I hope it is clear that my question involves accessing the other object's variables, and want to know if it is faux pas to use a direct variable access for something that is not "this".
No, absolutely not.
You should use the variable directly when you're inside the class' members, and use getters in every other situation (when you would get an error because val is private anyway).
public int getVal() is intended to present your gift(variable) within a box to the outside world (encapsulation). Do you give gifts yourself in a box? It's weird, so use the variable as it is.
You can use variables, but the current code does not compile. Probably, the return should be int instead of boolean.
Probably, your intention is to override the compareTo method from the Comparable interface
Adding an unnecessary getter reveals internal structure and this is an opportunity for increased coupling.
A truly well-encapsulated class has no setters and preferably no getters either. Rather than asking a class for some data and then compute something with it, the class should be responsible to compute something with its data and then return the result.
Use of accessors to restrict direct access to field variable is preferred over the use of public fields, however, making getters and setter for each and every field is overkill. It also depends on the situation though, sometimes you just want a dumb data object. Accessors should be added for field where they're really required. A class should expose larger behavior which happens to use its state, rather than a repository of state to be manipulated by other classes.
I'm trying to get a better understanding than I've been able to so far...it's to help me with class, but not with any specific homework assignment; I'm looking for more conceptual information that I've not found in my textbook or in the tutorials. On a purely theoretical level, I get why encapsulation is powerful for OO programming, but need a better understanding of what, specifically is going on. I keep confusing myself about the path through which data flows, and wonder where we're getting and setting data FROM. Hopefully this is not the exception to the "there are no stupid questions" rule.
Consider:
public class Employee
{
private int empNum;
public int getEmpNum()
{ return empNum; }
public void setEmpNum(int Emp)
{ empNum = emp; }
}
My interpretation of this: Using int Emp passed from somewhere, we set the declared empNum variable in the set... method. We then get... that variable and return it to the calling method. Is that a good understanding?
Further Consider:
import.javax.*
public class CreateEmp
{
public static void main(String[] args)
{
int ssn;
ssn = JOptionPane.showInputDialog(null,"enter ssn");
Employee newEmp = new Employee(123456789);
JOptionPane.showMessageDialog(null,"Employee ID " + newEmp.getEmpNum);
}
}
With this class, I don't need to explicitly set a variable because declaring new Employee(123456789) automagically sends that value to the set... method. The return in the Employee method returns the resulting value to the calling method and makes that variable available, in this case to my dialog box output. Do I have a handle on that?
Here's where I get confused. With my understanding as noted above--which may be off--I can never decide the best place to put logic. For instance: I would place the "enter employee number" dialog box in the Employee class, with a condition to run ONLY if the parameter passed to the method was null. In my mind, as I understand the data flow, the purpose of the class is to get an employee number. If one is not supplied as a default, one needs to be created. I'm not sure if this thinking is best practices, or if I'm setting myself up for trouble later.
I'd love to hear some thoughts about whether or not I'm properly understanding what's happening.
First, this site is to be used more for questions that can be concretely answered; not so much for theoretical questions.
Anyways, the first part with the 'get' and 'set' you understand fine. Now when you said that you do not need to explicitly set the employee number because you do 'new Employee ...' is not quite true. That would work if you had explicitly defined a constructor that takes an integer for an argument and then sets 'empNum' equal to the argued integer value.
Getters and setters are usually used in conjunction with the 'private' modifier. Setters can be used to control the input. For example, you can check if the provided value is greater than zero, where as you cannot if you give direct access. Getters just allow values to be retrieved, but to make changes you force the use of the corresponding setter (if any).
You are right about how if a value is not supplied you should set one by default. Consider that the value that you retrieve (if any) is to be used in a different class. What if the user never set a value? What if it's not something you expected? The different class, whatever it may be, still requires a value and you still need to pass something. By setting a default value, the different class can recognize that, "oh, this is a default value - this means that the user probably did not supply the correct input." By doing so, you create a relatively fail-safe application; you can keep on working even if the input is not what it is expected to be.
The point of using public accessors for private variables is to control how those variables are accessed and to insure that all of the internal state is kept consistent. For example, a class might have both an age and a birthdate variable. Setting the birthdate also implicitly sets the age. If direct access was given to these variables, then it would be possible to set them to inconsistent values (i.e. birthday says they are 30, but age set to 35). By using setters, we can insure that setting the birthdate will reset the age to be correct.
In this example, using setters would also allow us to convert the age variable into a generated property. Since age can be directly determined using the birthdate, you can create a getter for age and have it directly calculate and return the age without needing to store it anywhere.
If we use getters and setters to expose these object properties, we are free to switch out the implementations (such as removing the age variable and calculating it on the fly) without the users of our object needing to worry about it.
It depends how you are using the Employee object. If, upon construction, you always provide the employee number or one is automatically provided and the employee number is never set anywhere else, then you won't need the set method.
However, if at some point you are going to set the employee number to something else (perhaps an error was made and the number needs to be updated), then you will need to have a "set" method. In this case, it would probably be easiest to also call the "set" method from the constructor.
It really depends on how the Employee class will be used/instantiated.
You say
With this class, I don't need to explicitly set a variable because declaring new Employee(123456789) automagically sends that value to the set... method.
I'm pretty sure that's not true. Consider this: Java creates an Employee object and the constructor receives the value 123456789. How does it know to which variable it needs to assign that value? It doesn't know. There can be multiple variables that belong to that object so it doesn't know what 123456789 really means.
When you don't define a constructor in Java, it automatically creates one for you. But that one does not take any arguments, it's just a default constructor. Your code has several compile errors (for example, the import line for javax is wrong) so I'm guessing you're running a previously compiled version of your code. Remove all .class files in your project, fix compile errors and run again. It should give you an error. It'll also make the flow of data a lot easier to understand. The constructor should look something like this:
public Employee(int empNum) {
this.empNum = empNum;
}
It now makes a lot more sense that getEmpNum() knows which value to return.
With this class, I don't need to explicitly set a variable because declaring new Employee(123456789) automagically sends that value to the set... method. The return in the Employee method returns the resulting value to the calling method and makes that variable available, in this case to my dialog box output. Do I have a handle on that?
Your understanding is slightly wrong here. The statement
new Employee(123456789)
is creating a new Employee object by using a constructor method. Constructors usually take parameters which are used to set the internal member variables of the class.
So the complete Employee class would be -
public class Employee
{
private int empNum;
public Employee(int employeeNum) {
empNum = employeeNum;
}
public int getEmpNum() {
return empNum;
}
public void setEmpNum(int Emp) {
empNum = emp;
}
}
Am having some arguments say (String a, Treeset b, Set c)
and I try to get the class by arguments[i].getClass(); of the above arguments..
is Iit possible to get the class of the interface <Set>.
For example:
Class[] argumentTypes = new Class [arguments.length];
for (int i = 0 ; i < arguments.length ; i++)
{
argumentTypes[i] = arguments[i].getClass();
}
The code you've given will find the classes of the arguments (i.e. the values provided to the method) - but those can never be interfaces; they'll always be concrete implementations. (You can never pass "just a set" - always a reference to an object which is an instance of an implementation of the interface, or a null reference.)
It sounds like you want the types of the parameters - which you'd get via reflection if you absolutely had to, finding the Method and then getting the parameters from that with getParameterTypes. But given that you're within the method, you already know the parameter types, because they're at the top of the method... I'm not sure the best way of finding "the currently executing" method, if that's what you're after.
If you're just trying to get the class associated with Set, you can use Set.class of course. But again, it's not really clear what you're trying to do.
EDIT: Okay, judging from your comment, there are some logical problems with what you're trying to do. Going from the values of arguments to which method would be invoked is impossible in the general case, because you've lost information. Consider this, for example:
void foo(String x) {}
void foo(Object y) {}
foo("hello"); // Calls first method
foo((Object) "hello"); // Calls second method
Here the argument values are the same - but the expressions have a different type.
You can find all methods which would be valid for the argument values - modulo generic information lost by type erasure - using Class.isAssignableFrom. Does that help you enough?
Note that you'll also need to think carefully about how you handle null argument values, which would obviously be valid for any reference type parameter...
You can use http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#getInterfaces()
You will get the class what the caller provided.
I mean,in below class you will get HashSet.
Set set=new HashSet();
System.out.println(set.getClass());
You can do this in two ways given below
Set s = new //any class that implements it for example HashSet or TreeSet etc.;
s.getClass().getName(); //This will return the name of the subclass which is refered by s.
or if in other way can do it
Set s = null;
s.getClass();//This causes NullPointer Exception
Despite Java tutorials, Wikipedia searches, stackoverflow trolling, and hours of reading code samples, constructors still confuse the crap out of me. I've got three related questions that I've been trying to answer to help ME understand constructors a little better.
First, I've been under the impression that constructors need to be named the same as their classes. Consider:
public class Money {
public Money(long l) {
this.value = l;
}
public Money(String s) {
this.value = toLong(s);
}
public long getLong() {
return this.value;
}
public String getString() {
return toString(this.value);
}
}
I see this as four constructors...correct? So it appears that constructors not named the same as the class which contains them allowable. Can someone confirm that?
Second, I seem to have a block against understanding the set and get methods. Consider:
public class GetSetSample {
public int getFoo() {
return int Foo;
}
public void setFoo(int fooValue) {
int Foo = fooValue;
}
}
Why can't I just do this:
public class getFoo(int fooValue){
foo=fooValue;
}
and use foo = getFoo(12) from some other class/method?
The third question is a little more esoteric, but will help me conceive of the bigger picture...which is my learning style, and conducive to my ability to trace program flow when debugging. The get and set methods suggest a "to" and "from" relationship to me. e.g., Passing a value "to" a constructor, receiving the result "from" the get method. It seems to me though that the "to" and "from" will change depending on your perspective. I think that any setMethod is setting parameters for an object, even though the variable comes FROM another class or method, and the GetMethod is getting the resulting object (say, this.foo) with the appropriately set parameter. No matter where the get or set is used, in a main method or a standalone class with a single constructor, 'set' is always associated with sending a parameter and get is always associated with receiving an object with that parameter. Is that a good understanding? or am I missing a vital part?
Question 1:
I see this as four constructors...correct?
No, that class has two constructors and two methods. (getLong and getString are the methods.)
Question 2:
Why can't I just do this:
public class getFoo(int fooValue){
foo=fooValue;
}
Well, that's trying to declare a class with parameters, and also you're setting a value in a get method, which would be extremely weird. It's not clear what you're trying to achieve here, but that code is thoroughly invalid.
Question 3:
The get and set methods suggest a "to" and "from" relationship to me.
Well it's not really a relationship IMO. A relationship suggests something longer term than either of these methods. A setter typically changes the state of an object in some way, and a getter typically just returns some aspect of the state of an object. It's not really clear what the rest of your explanation meant, because you're playing somewhat fast and loose with terminology. For example: "get is always associated with receiving an object with that parameter" doesn't really make sense to me. Objects don't have parameters, methods/constructors do - and getters can fetch primitive values or references...
I suspect you would benefit from reading the "Classes" part of the Java tutorial, which talks about constructors and methods.
Regarding the first answer, there's only 2 constructors. The difference is on how they are going to be called (called using a string will use the construction having a string has a parameter and called using a long will use the other one). So to answer, yes a constructor has the same name as the class.
The two constructors :
public Money(long l) {
this.value = l;
}
public Money(String s) {
this.value = toLong(s);
}
Regarding the second answer, getters ans setters are not meant to be classes. They are supposed to be within the class itself.
Consider this example which uses getter and setters to get ans set value for the printer class :
public class Printer {
#Inject #Informal Greeting greeting;
private String name;
private String salutation;
public void createSalutation() {
this.salutation = greeting.greet(name);
}
public String getSalutation() {
return salutation;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
A good read of this link could definitly help you out !
Java oriented-object principles
You've shown 2 constructors, which do need to have the same name as the class.
You've also shown two "getter" methods, which return the value of the class variable in the form requested by the user. You can also create "setter" methods, which are used to transfer values into class variables.
You use a constructor to create an object of a particular class, and optionally to set some or all of its internal state (that is, its member variables).
You use setters and getters to isolate the class variables from the outside world, so you don't need to allow other code to access them directly. Why? Because, before a setter updates a variable, it can verify that the new value is valid, and that the operation doesn't violate any or the rules (the "business logic") that are required for the class to work properly.
So you could add a setter and update the constructor to use it:
public Money(long l) {
setValue(l);
}
public Money(String s) {
setValue(toLong(s));
}
// Example setter that validates `l` by prohibiting negative values
public Money setValue(long l) {
if (l < 0) {
// Warn about negative values
}
this.value = l;
return this; // Return the current object to allow chaining; see below.
}
Note that a setter usually doesn't need to return a value (that is, it can be type void), but it's often helpful to return the object itself. That allows you to write code like this:
Money earnings = new Money().setValue(4).setOtherField("foo");
This creates an object of type Money, sets various attributes, and stores it in the variable earnings. Clearly, this isn't terribly useful for a simple class like this, but it can be very helpful for more complex classes:
Paycheck check = new Paycheck("MyCompany")
.setEmployee("YourName")
.setSalary(50,000)
.setPaySchedule(Schedule.BIWEEKLY)
.setAccountNumber("1234567")
.setDefaultTaxRate();
I would like to try to answer your implied conceptual questions -- you've already got plenty of examples of this and that, so I'm just going to try to explain. I have no doubt you have heard most of this -- maybe all of this -- before, but am not sure and not sure which parts.
Object-oriented programming centers mostly around objects; an object is an amalgamation of code and data. You define objects by writing a class, and you create one or more copies of the object defined by that class with the class constructor (called instantiating the class).
A parallel in other languages: you can have a data structure of related items and a set of subroutines that operate on that data structure. Think of a class as a way of collecting the items in that data structure and the subroutines that operate on it into one unit.
After you have invoked a constructor, you have a copy of the data defined in that class and a way to refer to that copy. By referring to that instance when you invoke a class method, you operate on that copy of the data with the methods defined in that class.
If you were to do this in a non-OO language, you could have a routine that created a copy of the data structure in memory and then only use the methods prescribed for it on that data structure. You could have a pointer to the copy in memory and pass that pointer as a parameter to every subroutine that operated on it, and in fact that's the way some pre-OO systems were programmed.
A constructor is similar to a method call that returns a value; it involves (or can involve) the execution of statements, and it always returns an object of that class. There are also differences between a constructor and a method; until the constructor completes, for instance, the object is not fully created and shouldn't have some methods invoked on it.
So I hope that helped; if there are conceptual things you still have questions about, perhaps something in here will help you form a specific question so we can explain things further.
Many people have found that if they have spent years learning languages such as COBOL and FORTRAN then changing to OO programming involves unlearning the old languages. I certainly found this when I first tackled C++ 20 years ago. From your description you are clearly struggling with the concepts and I sympathize.
I don't think there is a simple recipe. Practice at the simple examples and don't be disheartened. Don't be afraid to ask on SO - if the questions are clearly asked you will get a useful answer.
Get a good IDE (Eclipse, Netbeans, etc.) which allows you to "look inside" objects with the debugger. Hopefully at some stage things will click!
Question 1 - Basic Java Classes:
There's pretty much only 3 things you're going to find in a Java class
Field/attribute (Depending on your language of origin)
Method
Constructor (Which looks like a special kind of method)
Every class is going to have a class name that shares the name of the file it's located in. So to expand Money out a bit:
Money.java
----------
public class Money {
// This is a field/attribute
Long value;
// This is a constructor
public Money() {
this.value = Long(0L);
}
// This is a method
public Long getValue() {
return value;
}
// Another method
public void makeMoney(Long moreMoney) {
this.value = this.value + moreMoney;
}
} // Everything in here is part of the Money class
The only distinction between a constructor and a method is that a constructor has no specified return value, which is declared as a type right before the name of a potential method. Constructors do have to be named the same as the class they are contained in, but why is implied in how they are written.
Another way of looking at it is if you remove all of the non-type related Java keywords (public, private etc., but not things like float and int) from the front of the method you're looking at (A list of which you can find here), is there anything left in front of the method?
With the Money we have at the moment, it would look like this:
Money()
Long getValue()
void makeMoney()
The constructor is the one that has no type for the return value, because it is implied in the declaration.
Question 2/3 - Get/Set methods:
I'm going to say something potentially controversial, but don't worry about these yet. Get/Set are essentially patterns for Object Oriented development, and generally good Java style, but they aren't required (Last I checked, Android development actually discourages their use when possible for optimization reasons). Moreover, not all fields in your objects will be accessible or mutable so writing them isn't mandatory.
If you declare all of your fields as public (Like the 'value' field is implied to be right now), you simple can do this:
Money myMoney = new Money(new Long(40L));
System.out.println(myMoney.value) // 40
myMoney.value = new Long(20L);
System.out.println(myMoney.value) // 20
Aside from that, the notion of get() and set() are just methods. There is nothing special about them at all. The main reason they exist is because for general Object-Oriented programming, you shouldn't have to directly modify the internal workings of an object (This is the principle of Encapsulation). Everything you should need to affect state or get something out of it should be handled by a method.
In a pithy one-liner: If you need to know the fields of an object to use it, you designed it incorrectly.
Big Picture
So what get() and set() really are is a pair of commonly written methods that happen to affect a field in an object in an extremely simple way (get() is a simple access to a field, set() is assignment to that field). It's just that other methods you write will happen to do more complicated stuff than that.
I would like to know if the following code should work:
if (M != 0){
Tools.Printer(stdnr);
}
Background Info:
I created a public class Tools with a few functions. One of the functions is the void Printer function. Is there a rule or something that if you want to use Tools.something you need to do assign the Tools.something to an integer / print it, etc. Or is Tools.Printer supposed to work on its own.
I ask this because I can't find anything wrong with my code. I would be glad if someone can help me right with the terms I used above - I suppose they are terribly wrong...
Thank a lot, Help would be greatly appreciated
If your method is a void type, it returns nothing, therefore you do not need to assign it to a variable (in fact, you'll get a compile time error if you do).
If it was instead a function, like it returned some value, for instance:
public String foo()
{
return "kdfldj";
}
You still don't necessary need to assign it to a variable. The returned value will just be discarded. For example, StringBuilder.append returns back the StringBuilder that you just appended to, but you can safely call it like this:
myStringBuilder.append("some text");
And ignore the return value.
However, if your Tools.Printer method is not a static method, you do need to create an instance of Tools, either assigned to a variable like this:
Tools tools = new Tools();
tools.Printer(stdnr);
or initialized without being placed in a variable:
new Tools().Printer(stdnr);
But if Printer is a static method, your code should be fine, since you are calling the method by the class it's contained in.