Constructor overloading in Java - when to use it? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Im a new programmer and I want to know when its best practice to use overloaded constructors and what makes it different from single primary constructor.

The short answer is: you should use overloading whenever you need it.
As a real-life example, take a look at the JLabel API: https://docs.oracle.com/javase/8/docs/api/javax/swing/JLabel.html
JLabel has quite a few constructors: one that just takes a String, one that takes a String and an icon, one that only takes an icon, and one that doesn't take any arguments at all.
You would use each constructor when you want to construct that kind of JLabel: one that displays a String, one that displays a String and an icon, one that only displays an icon, or one that doesn't display anything yet (until you call one of its setter functions).

Constructor overloading is useful when you want to allow user to create objects in multiple different ways.For example to be able to create a simple Student class object in following different ways:
new Student(45); // given student id
new Student("name"); // given student name
new Student(45,"name"); // given student registration id and name
This helps ease the task of creating objects according to our requirements. You can link this concept with various java API's as the provide a no of different ways to initialize an object of a class.
Also you can combine the Construstor Overloading with Constructor chaining.
Here is an examlple:
public Student (int id){
this(id,"ANY-DEFAULT-NAME"); // calls the constructor of same class with 2 params
}
public Student (String name){
this(ANY-DEFAULT-ID,name);// calls the constructor of same class with 2 params
}
public Student (int id,String name){
// here you can initialize the instance variables of the class.
}

You can overload a constructor based in your needs. For example,let's say that you have a simple class called Dog, that have some attributes like: Name,Breed, Birthday, Owner and skin color.
public class Dog {
private String name;
private String breed;
private Date birthday;
private String owner;
private String skinColor;
/*Getters and Setters*/
...
}
If you instance a object of type Dog and want to set a all or some of the attributes' values, you'll have to call all the setters methods of the object, but with the constructor, you can save that step passing the values directly every moment you instance the object.
Example:
public class Dog {
private String name;
private String breed;
private Date birthday;
private String owner;
private String skinColor;
public Dog(String name, String breed,Date birthday,String owner,String skinColor){
this.name = name;
this.breed = breed;
this.birthday = birthday;
this.owner = owner;
this.skinColor = skinColor;
}
/*Getters and Setters*/
...
}
Dog myDog = new Dog("Jose", "Chiguagua",new Date(),"Jhon","Brown");
If you want only instance the object with the name only, you can do it too. A good practice is, if you have an object with attributes that is necessary to fill in some point, provide the default constructor, if you do not provide it, you will always need to pass some values for instance a object. This give flexibility to the programmer.

Related

Setters on objects Java [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 2 years ago.
Improve this question
Hello so I'm having a bit of difficulties with a setter method on objects.
public class Company {
private String companyName;
public static int numberOfEmployees;
public Employees employees[];
public void setEmployees( String name, String heritage, String [] programmingLanguages, Salary d) {
Employees employee1 = new Programmer(name, heritage,programmingLanguages, d,d.getBasicBrutoSalary());
employees[numberOfEmployees] = employee1;
numberOfEmployees++;
}
So basicly this is a method defined in the 'company class' while making an Employees object who's using the parameters for making a 'Programmer'.
But that's not the deal, what I want tot do is by calling this setter method, automaticly create an object. So each time it's used, kind of increment the name of the object it's going to make.
So for example the first time I use it it makes an object called Employee1 and stores it in Employee[0].. second time I want it to store Employee2 into Employee[1].
Maybe I'm making this way too difficult but I'm just trying things out, and can't seem to find a way to make this work.
I suppose that Programmer object is subclass of Employees, or else it will not work. More or less it should look like the following:
public class Company {
private String companyName;
public static int numberOfEmployees;
public static Employees employees[];
public void setEmployees( String name, String heritage, String [] programmingLanguages, Salary d) {
numberOfEmployees++;
employees[numberOfEmployees] = new Programmer(name, heritage,programmingLanguages, d,d.getBasicBrutoSalary());;
}

Java : How to store Integer and String in array and retrieve values in another class? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a model: fase.java with Integers and Strings + getters and setters:
public class Fase implements Serializable {
private Integer age;
private String name;
}
I want to store both the Integer and String in a Array or ArrayList. I now use this:
public String[] getAllValues(){
String[] values = {age.toString(), name};
return values;
Then in dataServiceImpl.java I retrieve the data with:
user.getFase().getAllValues()[0];
and retrieve the age.
This works, but I have a lot more than age and name, and was thinking if I could put everything in Fase.java in one Array/ArrayList, because they are Integer and String, and then retrieve it in dataServiceImpl.java?
Something like this in Fase.java: ArrayList <Objects> f3Values = new ArrayList <Objects>();
or Fase [] f3Array = new Fase[34];
and then retrieve that in dataServiceImpl.java with: ArrayList<Fase3.Fase3Array> f3List = new ArrayList<Fase3.Fase3Array>();
and use something like: user.f3List[0]; ?
First, you should learn how Java works.
Is Java "pass-by-reference" or "pass-by-value"?
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Then, you should learn how to properly create an encapsulated class, by defining both constructor(s) and getters, methods, setters (if needed; note that setters in general break encapsulation) etc.
Then, you should understand that to aggregate data you:
create a class, i.e. definition object that holds all the necessary fields,
create a storage aggregate (array, ArrayList, Map, whatever),
3a. create an object of a given class, setting the values of the fields,
3b. add the object to the aggregate,
3c. goto 3a until the aggregate is filled with the data needed.
Explaining that on the code provided, you should first have
public class Fase implements Serializable {
private int age;
private String name;
public Fase( int age, String name ) {
this.age = age;
this.name = name;
}
public int getAge() { return age; }
public String getName() { return name; }
}
then you can create the aggregate, e.g.
int FASE_MAX = 34;
Fase[] fArray = new Fase[FASE_MAX];
ArrayList<Fase> fArrayList = new ArrayList<Fase>(FASE_MAX);
then you create the objects and add them to the aggregate, e.g.
for( int i = 0; i < FASE_MAX; i++ ) {
Fase newFase = new Fase( i, "John Doe" );
fArrayList.add( newFase );
fArray[i] = newFase;
}
then, and only then, you can access the aggregate:
Fase someFase = fArrayList.get( n );
Fase someOtherFase = fArray[n];
Your Fase class can have whatever members and however many members you like and you can access them all. If you want an array of Fase then create one and each element of the array will contain all the Fase members.
Fase[] myArray = new Fase[34];
You have an array of 34 "Fase's" just add whatever members you want to your Fase class.

Get the object that an object is assigned to, how?

I dont know how to really ask this.
But like...
Student stud1 = new Student("Shady");
Student stud2 = new Student("Nick");
Student stud3 = new Student("Name");
stud2.addBook(new Book(Book.BOOK_MISERABLES, 3););
Now if we assume we have the following variable in the Book class:
private Student owner;
And now the question, inside the constructor of "Book" -> Is it possible to get the "stud2" object it's being called to? Without adding an additional parameter to the constructor? If so, how? I think it's possible... So it will be something like this:
private Student owner;
public Book(int bookNum, int weeks){
this.owner = this.GET_THE_TARGET_THIS_IS_CALLED_ON;
this.bookNumber = bookNum;
this.time = weeks;
}
What you're asking is not directly possible. You will need to either
Pass a reference to the Student instance to your Book constructor
or
Use a setter inside the Book class to set the value of the owner field to your Student instance.
The latter would be a method that looks like this:
public void setOwner(Student owner) {
this.owner = owner;
}
Additionally, you may want to modify your Student.addBook method to call this setter, like this:
book.setOwner(this);
As you mentioned in your comment, you can traverse the stack using Thread.currentThread().getStackTrace() However, you'll be unable to obtain an object reference using that technique. You can obtain the class or method name but the uses for that are limited unless you intend to construct a new instance. That's all highly unorthodox and not at all appropriate for this situation.

Take specific value from specific line from 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 8 years ago.
Improve this question
I have created an ArrayList which contains some infos .
Every line has this pattern : name age sex job .
I'm searching for a way to take for example the every value separately and to assign them in different variables. I've search the web , but I came out to nothing ! So if there is someone that could help me I would appreciate it !
I have no idea how to do it so I can't provide code ! Soory I'm newbie in java .
Create a class Person that will hold your data:
class Person {
private String name;
private int age;
private String sex;
private String job;
//class constructor...
//getters and setters...
}
Then, read the file. For every line in the file, create an instance of Person class and store it in a List. I'll do this in pseudocode, it's up to you the concrete implementation (otherwise it would be me doing your homework =\):
List<Person> people <- new ArrayList<Person>()
open_file(theFile)
while not_end_of_file
String name <- read_text
String age <- read_int
String sex <- read_text
String job <- read_text
Person person <- new Person()
person->setName(name)
//similar for other fields...
people->add(person)
end while
Sounds like you have a List of Strings. If so, you could call the String split(String regex) method to get a String[] back.
I think what you need to do is create a Person object which would contain a name, age, sex and job.
Then you could create an Arraylist of type Person.
List<Person> people = new ArrayList<Person>();
The person class would look something like this:
public class Person {
String name, sex, jobTitle;
int age;
public Person(String name){
this.name = name;
}
}

Dynamic variable names in Java so each new object has separate name

How can I do such a thing?
String N = jTextField0.getText();
MyClass (N) = new Myclass();
Is it even possibe?
Or as my question's explains, how can I just make a method to create a new object of my specified class just with a different name each time I call it.
I really searched everywhere with no luck.
Thanks in Advance
P.S.
I wish you guys can excuse me for not being clear enough, Just to say it as it is, I made a textfield to get the name of someone who wants to make an account, and I made a class named "Customer". and a button named "Add". Now I want every time "Add" is clicked, compiler take what is in my textfield and make an object of the class "Customer" named with what it took from the textfield
It was too hard to read it in comments so I updated my question again, so sorry.
I'm stuck so bad. I suppose my problem is that I didn't "understand" what you did and only tried to copy it. This is what I wrote:
private void AddB0MouseClicked(java.awt.event.MouseEvent evt) {
String name = NameT0.getText();
Customer instance = new Customer(Name);
Customer.customers.add(instance);
and this is my Customer class:
public class Customer{
String name;
public Customer(String name){
this.name = name;
}
public String getName(){
return name;
}
static ArrayList<Customer> customers = new ArrayList<Customer>();
Variable names must be determined at compile time, they are not even part of the generated code. So there is no way to do that.
If you want to be able to give your objects names, you can use
Map<String, MyClass> map = new HashMap<>();
Add objects to the map like this (e.g):
map.put(userInput, new MyClass());
and retrieve objects like this:
MyClass mc = map.get(userInput);
I'm not entirely sure what you mean by...
how can I just make a method to create a new object of my specified
class just with a different name each time I call it
...but if I'm interpreting you correctly, I believe what you're trying to do as make MyClass accept a constructor parameter. You can do:
public class MyClass {
private String name;
public MyClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then to create a new instance of MyClass, do:
String name = jTextField0.getText();
MyClass instance = new MyClass(name);
instance.getName(); // returns the name it was given
EDIT
Since you've added clarifications in the comments since I first answered this question, I thought I would update the answer to portray more of the functionality that you're looking for.
To keep track of the MyClass instances, you can add them to an ArrayList. ArrayList objects can be instantiated as follows:
ArrayList<MyClass> customers = new ArrayList<MyClass>();
Then for each MyClass instance you wish to add, do the following:
customers.add(instance);
Note that the ArrayList should not be reinstantiated for each instance that you wish to add; you should only instantiate the ArrayList once.

Categories

Resources