Overloaded constructors in a class - java

I'm doing a project with overloaded constructors in a class and I'm a little stuck, below is what I'm supposed to be doing with the overloaded constructors:
"One that allows first, middle, and last names to be passed as Strings with an int for age
One that accepts a Name object reference, and an age as an int
Make a new Name inside Person, copying the references for the parts of the name."
I'm not quite sure what to do with my code, here is what I got:
public class Person {
int age;
Name aPersonHasAName;
Name newPerson = new Name();
public Person(String firstName, String middleName, String lastName, int age) {
newPerson.firstName = firstName;
newPerson.middleName = middleName;
newPerson.lastName = lastName;
}
public Person(Name aPersonHasAName, int age) {
}
public void details() {
System.out.println(aPersonHasAName + " age: " + age);
}
}
I'm just lost as to what I'm supposed to be typing. I believe I've done the first overloaded constructor, but I am new to this.
So what should I be doing to make this work with overloaded constructors?
I think having the code from the other two classes might help.
Here is PersonTester:
public class PersonTester {
public static void main(String[] args) {
Person person1 = new Person("a1", "b1", "c1", 11);
Person person2 = new Person(new Name("a2", "b2", "c2"), 22);
Person person3 = new Person(new Name("a3", "c3"), 33);
Person person4 = new Person(new Name("a4"), 44);
Person person5 = new Person(new Name(), 55);
System.out.println(person1.details());
System.out.println(person2.details());
System.out.println(person3.details());
System.out.println(person4.details());
System.out.println(person5.details());
}
}
Then here is the Name class:
public class Name {
String firstName;
String middleName;
String lastName;
public Name(String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
public Name(String firstName, String lastName) {
this(firstName, "", lastName);
}
public Name(String firstName) {
this(firstName, "", "");
}
public Name() {
this("", "", "");
}
public String getLastName() {
return lastName;
}
public String getMiddleName() {
return middleName;
}
public String getFirstName() {
return firstName;
}
public String getFullName(String nameString) {
StringBuilder build = new StringBuilder();
build.append(nameString);
build.deleteCharAt(nameString.length() - 1);
build.insert(0, build.hashCode());
return build.toString();
}
}
The problem I am having now is the error message in PersonTester which is: The method println(boolean) in the type PrintStream is not applicable for the arguments (void)
I just need to know what in which class needs to be fixed to make it work.
I am very new to Java and object oriented programming.

So far so good. But eventually you'll reach a point where you duplicate a fair bit of code.
The constructor
public Person(String firstName, String middleName, String lastName, int age) {
is the most comprehensive one in the sense that it takes in all the possible data.
With the other constructors, say one that takes a last name and an age, you can use delegating constructors:
public Person(String lastName, int age) {
this(null, null, lastName, age); /*calls the other constructor*/
}
If you can't make such an assumption then you'll need to split up the name string by hand.

Updating your code:
public Person(String firstName, String middleName, String lastName, int age) {
newPerson.firstName = firstName;
newPerson.middleName =
newPerson.lastName = lastName;
this.age = age; //<---- was missing in your code
}
And your second contructor may look like this:
public Person(Name aPersonHasAName, int age) {
this.newPerson = aPersonHasAName;
this.age = age;
}
These contructors are implemented as you needed.
Notice that you already done your overloading, if you got multiple constructors with not the same titles you contructors overloading

public class Person {
int age;
Name aPersonHasAName;
public Person(String firstName, String middleName, String lastName, int age) {
aPersonHasAName = new Name();
aPersonHasAName.firstName = firstName;
aPersonHasAName.middleName = middleName;
aPersonHasAName.lastName = lastName;
this.age = age;
}
public Person(Name aPersonHasAName, int age) {
this.aPersonHasAName = aPersonHasAName;
this.age = age;
}
public void details() {
System.out.println(aPersonHasAName + " age: " + age);
}
}
I guess it also depends on if Name has a constructor for firstName, middleName, lastName

Related

Disaster management Class shows "cannot be applied" to User u2 error

I'm working on this lab where I'm creating a hypothetical disaster management system for people to put information about disasters with Java. Within the code, there are two classes with the same name User. The tutorial for the lab says that line 75 with user u2 is supposed to use an Emergency Contact class by using the following code:
User u2 = new User("Marlena", "Evans","6088861222", "me#daysofourlives.com");
However, with this, the console brings up this error:
'User(java.lang.String, java.lang.String, java.lang.String, java.lang.String)' in 'User' cannot be applied to '(java.lang.String, java.lang.String, boolean, int, java.lang.String, java.lang.String)'
so I changed it to:
User u2 = new User("Marlena", "Evans", false, 30, "6088861222","me#daysofourlives.com");
which removed the error.
I need a fresh set of eyes on this. Can someone look at this and tell me why the tutorial's code isn't working?
Here is what the code is supposed to look like:
and here is my code:
//import java.sql.Timestamp (package already active)
public class User {
private String firstName;
private String lastName;
private boolean gender; //true - male; false - female
private int age;
private BloodType blood;
private String telephone;
private String email;
private User emergencyContact;
public void setContact(User u){
this.emergencyContact = u;
}
public User (
String firstName,
String lastName,
boolean gender,
int age,
String blood,
String telephone,
String email
) {
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.age = age;
this.blood = BloodType.fromString(blood);
this.telephone = telephone;
this.email = email;
}
public String getFirstName(){
return this.firstName;
}
public String getLastName(){
return this.lastName;
}
public boolean getGender(){
return this.gender;
}
public int getAge() {
return this.age;
}
public String getTelephone(){
return this.telephone;
}
public String getEmail() {
return this.email;
}
public BloodType getBlood() {
return this.blood;
}
public User getEmergencyContact() {
return this.emergencyContact;
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO
//Here is an example of using the new user constructor
User u1 = new User("John","Black",true,25, "6085551234","jb#daysof" +
"ourlives.com");
//This example uses the Emergency Contact Constructor to create a new emergency contact
User u2 = new User("Marlena", "Evans", false, 30, "6088861222","me#daysofourlives.com");
u1.setContact(u2); //This means Marlena is the Emergency Contact for John
System.out.println("User: " + u1.firstName + " has an emergency contact of: " + u1.emergencyContact.getFirstName());
}
public User (
String firstName,
String lastName,
boolean gender,
int age,
String telephone,
String email
){
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.age = age;
this.email = email;
}
}
Thank you and as always, let me know if you need more context to help me.
You are missing an additional constructor with the reduced number of arguments that constructor call in line 75 is using.
Add this to your User class:
public User(String firstName, String lastName, String telephone, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.telephone = telephone;
this.email = email;
}
Also, in the main class, you are accessing firstName and emergencyContact fields, but these are private fields, so either set them to public or add a setter method.

How to create objects for parameterized constructors in Java, when we have two classes with the same attributes?

I have class Student, that has first name, last name and age, and a method to print the name and the age of the student.
public class Student {
private String firstName;
private String LastName;
private int age;
}
Student() {}
public Student(String firstName, String lastName, int age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void printInfoStudent(){
System.out.println("Student: " + firstName + " " + lastName + ", " + age);
}
And I have a second class Professor, that has first name, last name, and university. And I have a method to print the info about the professor.
public class Professor {
private Student firstName;
private Student lastName;
private String uni;
}
Professor() {
}
public Professor(Student firstName, Student lastName, String uni) {
this.firstName = firstName;
this.lastName = lastName;
this.uni = uni;
}
public Student getFirstName() {
return firstName;
}
public void setFirstName(Student firstName) {
this.firstName = firstName;
}
public Student getLastName() {
return lastName;
}
public void setLastName(Student lastName) {
this.lastName = lastName;
}
public String getUni() {
return uni;
}
public void setUni(String uni) {
this.uni = uni;
}
public void printInfo(){
System.out.println("Professor: " + firstName + " " + lastName + ", uni: " + university);
}
And in the main class I create two objects.
Student s = new Student("John", "John", 24);
Professor p = new Professor("Johnny", "Johnny", "Oxford");
printInfo.p();
printInfoStudent.s();
And it's showing me an error: String cannot be converted to Student, can someone explain why is that, and how should I fix this?
You've created the objects properly but are not calling their functions properly.
Student s = new Student("John", "John", 24);
Professor p = new Professor("Johnny", "Johnny", "Oxford");
p.printInfo()
s.printInfoStudent();
You need to name the instance first then specify the method inside to call after the dot.

Error The constructor Family(String, String, int) is undefined

I am fairly new to Java. I am getting an error "The constructor Family(String, String, int) is undefined". Im not sure what this means. Need a bit of help here please.
EDIT: I was missing the extra 3 parameters and also was missing quotes around 31.
Main.java
public class Main {
public static void main(String[] args){
Family person = new Family("CHRIS", "PEREZ", 31);
String person1 = person.getPerson();
System.out.println(person1);
}
}
Family.java
public class Family {
String firstName;
String lastName;
int age;
int phoneNumber;
String dob;
String married;
public Family(String firstName, String lastName, int age, int phoneNumber,
String dob, String married) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.phoneNumber = phoneNumber;
this.dob = dob;
this.married = married;
public String getPerson() {
return ("Hi my name is"+this.firstName+" "+ this.lastName+"."+"I am "+this.age+" years old.");
}
}
This is because your Family class only has a six-argument constructor requiring all of the six fields to be provided. Your call:
Family person = new Family("CHRIS", "PEREZ", 31);
only provides three of the six required. You could override the constructor, for instance:
public Family(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
...
}
but you should do something with the rest of the fields that you didn't provide here that you provide in the other constructor.
You're calling the Family class constructor like this:
Family person = new Family("CHRIS", "PEREZ", 31);
But the only constructor in the class is defined like this:
public Family(String firstName, String lastName, int age, int phoneNumber,
String dob, String married) {
See that it has more parameters than you're passing in: phoneNumber, dob, married. In Java you have to give values to all parameters:
Family person = new Family("CHRIS", "PEREZ", 31, 123456, "5/Apr/1975", "who's asking");
Or, you need to define a new constructor that needs only firstName, lastName and age.

Is it possible to return superclass object from initialized subclass without initializing superclass

I have the following code:
public class Person
{
final String firstName;
final String lastName;
final int age;
final UUID identification;
public Person(final String firstName, final String lastName, final int age)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.identification = UUID.randomUUID();
}
protected Person(final String firstName, final String lastName, final int age, final UUID identification)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.identification = identification;
}
/*
Getter functions
*/
public Person asPerson()
{
return this;
}
/*
Hash and Equals code
Equals checks for first/lastName, age, and identification
*/
}
public class Employee extends Person
{
final String occupation;
final float salary;
public Employee(final String firstName, final String lastName, final int age, final String occupation, final float salary)
{
super(firstName, lastName, age);
this.occupation = occupation;
this.salary = salary;
}
public Employee(final Person person, final String occupation, final float salary)
{
super(person.getFirstName(), person.getLastName, person.getAge(), person.getID());
this.occupation = occupation;
this.salary = salary;
}
/*
Getter functions for occupation and salary
*/
#Override
public Person asPerson()
{
return new Person(firstName, lastName, age, identification);
}
/*
Hash and Equals code
Equals checks for equality in occupation and salary
*/
}
public class Volunteer extends Person
{
final String location;
public Volunteer(final String firstName, final String lastName, final int age, final String location)
{
super(firstName, lastName, age);
this.location = location;
}
public Volunteer(final Person person, final String location)
{
super(person.getFirstName(), person.getLastName(), person.getAge(), person.getID());
this.location = location;
}
/*
Getter for location
*/
#Override
public Person asPerson()
{
return new Person(firstName, lastName, age, identification);
}
/*
Hash and Equals
Equals checks for equality in location.
*/
}
public Main
{
public static void main(String[] args)
{
final Person person = new Person("Man", "Fredman", 25);
final Person employee = new Employee(person, "Driver", 65000.0f);
final Person volunteer = new Volunteer(person, "Philly");
final boolean eqality = compareVtoE(volunteer, employee);
System.out.println(equality);
}
private boolean compareVtoE(final Person volunteer, final Person employee)
{
return volunteer.asPerson().equals(employee.asPerson());
}
}
Having an Employee variable already defined, is there a way in the asPerson function in Employee to return the superclass instance without having to call new Person(...)?
My current work-around is using a protected constructor to take in identification, but I would think there is a better way to go about this.
Edit
I have expanded the example. Say I have a Volunteer and an Employee that both extends Person and can take in a Person object in the constructor. They can both be the same person, but do different things. To see if one volunteer is the same as an employee, I need a way to get the Person object, without changing the UUID. My work-around is using a protected constructor in Person that takes in the UUID, used in the subclass constructors with super. I want to avoid using the constructor in asPerson(), creating a new instance of Person.
I am pretty sure there is no way to do what you are asking for as it would require changing the object without changing it, but here are two possible solutions to your comparison problem:
Override the equals method in Person class so you can compare people regardless of their role (employee or volunteer):
#Override
public boolean equals(Object other) {
if (other instanceof Person) {
return identification.equals(((Person)other).identification);
}
return false;
}
If for some reason you can not use equals, for example you need to override it in derived classes with different functionality, just create a isSamePerson function like this:
public boolean isSamePerson(Person other) {
if (other != null) return identification.equals(other.identification);
return false;
}
This will save you unnecessary object duplication, and the danger of loosing track of the people.

Why does this output wrong (get/set methods)

Just going through get/set methods and I'm having trouble with my output. Instead of displaying the First/Last name of the object it is displaying null/null.
Could anyone offer any insight, i'm not familiar with get/set methods.
Code
public class Person {
private String firstName;
private String lastName;
public Person (String a, String b){
a = firstName;
b = lastName;
}
public String getfirstName(){
return firstName;
}
public void setfirstName(){
this.firstName = firstName;
}
public String getlastName(){
return lastName;
}
public void setlastName(){
this.lastName = lastName;
}
public String toString() {
String s = "First name:" + firstName + "Last name:" + lastName;
return s;
}
}
This is my class just to create the object and run to toString method
public class PersonDriver {
public static void main(String[]args){
Person p1 = new Person ("Thomas", "Brown");
System.out.print(p1.toString());
}
}
You need to assign the parameters to the instance variables and not the reverse. What you're doing currently is reassigning a and b which were passed to the constructor, whereas you need to assign the values of a and b to the firstName and lastname fields of the class.
public Person (String a, String b){
firstName = a;
lastName = b;
}
You inverted the variables within your constructor
You need Change below code
public Person (String a, String b){
a = firstName;
b = lastName;
}
to
public Person (String a, String b){
firstName = a;
lastName = b;
}
Primarily setters has to be
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
Your setters should take an argument - the value to be set. Your constructor should assing the values of the arguments to the class properties not the other way round.
I think the constructor has to be like
public Person (String a, String b){
firstName = a;
lastName = b;
}
You need to swap the variabels. You assign the value of the object the parameters.
public Person (String a, String b){
firstName= a;
lastName= b;
}
Also your set method are useless without parameters :
public void setlastName(String parameter){
this.lastName = parameter;
}
You sure your methods shouldn't be more in line with this?
public class Person {
private String firstName;
private String lastName;
public Person (String a, String b){
firstName=a;
lastName=b;
}
public String getfirstName(){
return firstName;
}
public void setfirstName(String firstName){
this.firstName = firstName;
}
public String getlastName(){
return lastName;
}
public void setlastName(String lastName){
this.lastName = lastName;
}
public String toString() {
String s = "First name:" + firstName + "Last name:" + lastName;
return s;
}
}
You need to pass the setter methods the values you would want to set the variables to. Apart from that, like the others mentioned, you swapped the variable names in the constructor. :)

Categories