Is there a way of making optional atributes in java? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to code this class in java. I thought of making a bunch of constructors but i dont think thats the best way to do it. Id like to know if java has some sort of optional parameters or attributes to make this simpler.

You can do it with one constructor with varargs, since all fields of your class are of type String:
public class Address {
private String street;
private String city;
private String postalCode;
private String state;
private String country;
public Address(String... params) {
street = params[0];
city = params[1];
//etc. Just take care to pass the arguments in the order you are
//assigning them when you call the constructor. Also check the size
//of varargs first so you don't assign arguments that don't exist.
}
}
And then call it like so to set only the street and city:
Address adress = new Address("myStreet", "myCity");
An alternative is to have one constructor with all the arguments, and if you don't want to set a value, pass null to the constructor in place of the corresponding parameter:
Address adress = new Address("myStreet", "myCity", null, null, null);

Related

Java class has only one constructor, no parameter for constructor, all instances of that class will point to the same object in the heap? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Have the following case:
class Bond {
private static int price = 5;
public boolean sell() {
if(price<10) {
price++;
return true;
} else if(price>=10) {
return false;
}
return false;
}
public static void main(String[] cash) {
new Bond().sell();
new Bond().sell();
new Bond().sell();
System.out.print(price);
Bond bond1=new Bond();
System.out.print(price);
}
}
It will print: 8 9.
Will all instances that will be made, will point to the same object in the heap?
There's a very simple rule in Java: new SomethingOrOther() will always create a new object (unless it somehow produces an exception).
So the answer is obviously: no, the main method you posted will create 4 instances of Bond.
Those instances happen to not have any fields that makes them different in any interesting way, but they are distinct instances.
The reason it "looks like" only one instance exists is that your price field is static, which means it belongs to the class Bond itself and not to an individual instance, which also means there's only one price ever, no matter how many instances you have (yes, even if there are no instances at all).
Remove static keyword of "price" to answer it yourself.
static variables hold the same value across all the object instances.

Setting the Value to an Object by using Void or return type approach [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have Employee class and I am trying to set a value to employee name property:
public class Employee {
private String name;
private String id;
// setters and getters
}
I have got two options: by using void or using a return type.
public class EmpClient {
public static void main(String[] args) {
Employee emp = new Employee();
EmpClient emp_client = new EmpClient();
emp_client.setNameToEmployee(emp);
System.out.println(emp.getName());
}
public void setNameUsingVoid(Employee emp) {
emp.setName("Mark");
}
public Employee setNameToEmployee(Employee emp) {
emp.setName("Taylor");
return emp;
}
}
This is my code and through both the approaches, it works.
Please let me know what is the preferred and more efficient way? What are the pros and cons of using each of the methods, and under what circumstances should they be used?
It depends on what you want the method to do. For most cases setNameUsingVoid() method would be suitable. You want to assign a name to the employee and this method achieves that.
When instead you have this statement in your main method.
setNameToEmployee(emp);
The desired assignment is done and additionally, a reference is also returned. Here you are not using the returned value, so it is just unnecessary extra work. So if you are going to use the statement in the above fashion, use setNameUsingVoid() instead.
Note: According to the Java Language Specification, the above statement is a valid statement though the returned value is not being used. For more info on the validity of such statements
If instead you were to use setNameToEmployee() in this way:
Employee e1 = setNameToEmployee(emp);
You should opt for using this function over the other one. However in this specific use case the statement makes no sense at all because you are idly making a second copy of your Employee object. Summing up:
In this case (or any case where you pass a reference at return the same thing), it is best to use setNameUsingVoid(), as it is very difficult to think of a case where setNameToEmployee() might actually be beneficial.

Wrapping an Integer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need to make a constructor that accepts an integer to be wrapped. I currently have:
public class IntegerRateable implements Rateable {
private Integer object;
public IntegerRateable(Integer object) {
this.object = new Integer(object);
}
I am unsure what is wrong with my code. I was under the impression that this should allow it to be wrapped.
If what you want is, your IntegerRateable class to contain an Integer as member variable, try this:
public class IntegerRateable implements Rateable {
private Integer object;
public IntegerRateable (int number) {
this.object = number;
}
Then, just instantiate IntegerRateable object as:
IntegerRateable integerRateable = new IntegerRateable(5);
You may first want to check your braces, you're missing a closing brace }.
If that's not the problem, I'am assuming that the problem is in this line
this.object = new Integer(object); . There is nothing wrong with this, it's just that it using the Integer constructor has been deprecated which you can find out more about here https://docs.oracle.com/javase/9/docs/api/java/lang/Integer.html#Integer-int-
So the preferred way of doing it would be to do this.object = new Integer.valueOf(object);
EDIT: Although, I don't see a point in doing this since you can just do this.object = object;

How to add multiple values to an Object ArrayList? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The problem should be on the createClass() method... is it wrong to use classes.add(this)?
private static ArrayList<VirtualClass> classes = new ArrayList<VirtualClass>();
private boolean isPrivate;
private String className;
private String methodName;
public void setVirtualClass(String name, String method, boolean isP){
this.className = name;
this.isPrivate = isP;
this.methodName = method;
}
public void createClass(String name, String method, boolean isP){
this.className = name;
this.isPrivate = isP;
this.methodName = method;
classes.add(this);
}
More details on the problem: Failed to store values in ArrayList of class object. (CODE EDITED)
I suppose you want to keep a record of all created classes?
It is generally bad practice to pass out this in a constructor because, by definition, this hasn't been constructed yet. In this instance I don't think it will cause problems but it certainly doesn't smell right.
I would consider using a static factory method or another form of factory pattern so that you can split up object creation and the storing of instances.
No one can tell you whether it is right or wrong unless you tell what you are trying to do.
If what you are doing is something like : (assume your class is called Foo)
Foo foo = new Foo();
foo.createClass("Blablabla", "method1", true);
foo.createClass("AnotherClass", "method2", true);
something like that, then yes, you are probably wrong. Because what you are doing is simply changing the only Foo instance with different attribute, and adding the same object to the list.

List<String> with a Value 'Integer' [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Are there any alternatives to? (1 group )
class team {
List<String> team = new ArrayList<String>
int score = 0;
}
Is there an object that that store a List or Set 'String', that can hold a value of a Integer?
Thanks in advance.
It sounds like you need a Score object:
class Score
{
int points;
String groupName;
}
and then a List<Score> of them
What you probably want is a new type that holds both the String and the int that you care about, e.g.:
public class Score {
String group;
int score;
}
...
List<Score> scores = new ArrayList<Score>();
To answer your original question, though: The narrowest common type between String and Integer is Object, and you can construct such a List:
List<Object> group = new ArrayList<Object>();
group.add("string");
group.add(1);
Of course, this isn't restrictive to just String and Integer types, you can add any type of object.
Alternatively, you could coerce your Integer into a String:
String someNumber = String.valueOf(1);
Or construct a new class that is more restrictive, and acts as a kind of union:
public class StringOrInteger {
private final Object value;
public StringOrInteger(String string) {
value = string;
}
public StringOrInteger(Integer integer) {
value = integer;
}
public Object getValue() {
return value;
}
}
...and then have a list of these:
List<StringOrInteger> group = new ArrayList<StringOrInteger>();
(which will be at least compile-time restrictive)
You could get fancier with the class, and make it so that it returns a correctly cast object, but I suppose it depends on your use-case where you want to go with this.

Categories