Same Constructor Name Error - java

Okay so I'm trying to make more than one constructor with the same name. I'm getting an error and I am not sure why.I'm basically trying to make it so that when a player inputs their name, it will still work even if they don't input a specific field such as a suffix, etc. I'm aware I still have to add the setters and getters later and all that but I'm just trying to get the constructors set up right now. Any idea as to why it is giving me an error?
public class Name {
private String firstName;
private String middleInitial;
private String lastName;
private String suffix;
public String playerName(String firstName, String middleInitial, String lastName, String suffix){
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = lastName;
this.suffix = suffix;
return suffix + firstName + middleInitial + lastName;
}
public String playerName(String firstName, String lastName){
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = lastName;
this.suffix = suffix;
return suffix + firstName + middleInitial + lastName;
}
public String playerName(String firstName, String middleInitial, String lastName){ //this is where the error is. "Duplicate method playerName (String String String) in type Name"
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = lastName;
this.suffix = suffix;
return suffix + firstName + middleInitial + lastName;
}
public String playerName(String firstName, String lastName, String suffix){//same error here
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = lastName;
this.suffix = suffix;
return suffix + firstName + middleInitial + lastName;
}

If you were to call
obj.playerName ("string1", "string2", "string3");
how would java know whether this was
public String playerName(String firstName, String middleInitial, String lastName)
or
public String playerName(String firstName, String lastName, String suffix)

Lets take the constructor where you have the error
public String playerName(String firstName, String middleInitial, String lastName) { /* error */ }
Now this is another one where you have the same error
public String playerName(String firstName, String lastName, String suffix){ /* same error */ }
That is because your are using same DATA TYPE for the arguments in both of them and same number of arguments. So here java won't be able to decide which one to call when you use one of these.
I hope this is clear for you now...

When overloading methods (or constructors), you can only have methods that differ in their type signatures. Thus, only one method (of the same name) that takes three String parameters. However, you currently have no constructors. What I think you really wanted was to create Name instances, perhaps to also have getters and setters and finally to override toString (so you can get the Name as a String). Something like,
public class Name {
private String firstName;
private String middleInitial = "";
private String lastName;
private String suffix = "";
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Name(String firstName, String middleInitial, String lastName) {
this(firstName, lastName);
this.middleInitial = middleInitial;
}
public Name(String firstName, String middleInitial, String lastName,
String suffix) {
this(firstName, lastName, middleInitial);
this.suffix = suffix;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleInitial() {
return middleInitial;
}
public void setMiddleInitial(String middleInitial) {
this.middleInitial = middleInitial;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(firstName);
if (sb.length() > 0) {
sb.append(' ');
}
if (middleInitial.length() > 0) {
sb.append(middleInitial).append(' ');
}
sb.append(lastName);
if (suffix.length() > 0) {
sb.append(' ');
sb.append(suffix);
}
return sb.toString();
}
}
The example toString is performing String concatenation, and you could do the less efficient
#Override
public String toString() {
String str = firstName;
if (str.length() > 0) {
str += " "; // <-- str = str + " ";
}
if (middleInitial.length() > 0) {
str += middleInitial + " ";
}
str += lastName;
if (suffix.length() > 0) {
str += " " + suffix;
}
return str;
}

Related

Creating Address Attribute in Java

package week3;
import java.util.ArrayList;
public abstract class TaxPayer {
private final String TFN;
private String firstName;
private String lastName;
private double income;
private Address address(int streetNumber, String streetName, String suburb,
String city, String state, int postcode);
public TaxPayer(String TFN, String firstName, String lastName, double income,
Address address) {
this.TFN = TFN;
this.firstName = firstName;
this.lastName = lastName;
this.income = income;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public double getIncome() {
return income;
}
public Address getAddress() {
return address;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setIncome(double income) {
this.income = income;
}
public void setAddress(Address i) {
}
public String getFullName() {
return getFirstName() + " " + getLastName();
}
#Override
public String toString() {
return TFN + " " + firstName + " " + lastName + " "
+ income;
}
public static double calcTax(double income) {
return 1;
}
public double calcTax() {
return 1;
}
public static void printArrayListToConsole(ArrayList<TaxPayer> Array) {
for (TaxPayer d : Array) {
System.out.println(d);
}
}
}
package week3;
public class Address {
int streetNumber;
String streetName;
String suburb;
String city;
String state;
int postcode;
public Address(int streetNumber, String streetName, String suburb,
String city, String state, int postcode) {
this.streetNumber = streetNumber;
this.streetName = streetName;
this.suburb = suburb;
this.city = city;
this.state = state;
this.postcode = postcode;
}
#Override
public String toString() {
return streetNumber + " " + streetName + " " + suburb + " " + city + " "
+ state + " " + postcode;
}
}
So, my problem is in creating the address attribute, which must be private. I think I've made the other class correctly yet it still isn't working. As well as this, the attribute isn't working with the fields I try to put in it (streetNumber, streetName, etc), it's coming up with the error 'missing method body, or declare abstract' but I'm unsure why. Any help is appreciated!
private Address address(int streetNumber, String streetName, String suburb,
String city, String state, int postcode);// this is a method not a attribute
Make private attribute of Address Class.
public abstract class TaxPayer {
.
.
.
private Address address; // this is attribute.
.
.
.
//One way is passing the all address attributes in constructor
public TaxPayer(String TFN, String firstName, String lastName, double income,int streetNumber, String streetName, String suburb,
String city, String state, int postcode) {
this.TFN = TFN;
this.firstName = firstName;
this.lastName = lastName;
this.income = income;
this.address = new Address(streetNumber, streetName, String suburb,city, state, postcode);
}
}
second option is use same constructor and make a Address objectin main class and pass into that constructor like :
public TaxPayer(String TFN, String firstName, String lastName, double income,Address address) {
this.TFN = TFN;
this.firstName = firstName;
this.lastName = lastName;
this.income = income;
this.address = address;
}
And while creating Tax Payer Object first create Address Object and pass it.
Address address= new Address(streetNumber, streetName, String suburb,city, state, postcode);
TaxPayer tp= new TaxPayer(TFN, firstName, lastName, income,address);
private Address address(int streetNumber, String streetName, String suburb,
String city, String state, int postcode);
You have to declaring a variable of Address type but this is not the way to declare a variable.
Replace the above code of TaxPayer class with just this
private Address address;

program calling default constructor? [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 5 years ago.
Improve this question
Beginner here.
I cant get my head around why this code outputs the default halfway through. Can anyone take look?
sorry if the format is wrong, first time posting and will fix if not correct.
public class officemanager {
public static void main(String[] args) {
Staffmember aStaffMember = new Staffmember("Steven", "bob");
System.out.println(aStaffMember.toString());
Programmer appleprg = new Programmer("Marion", "bob", "Java");
appleprg.getLanguage();
System.out.println(appleprg.toString());
Doctor dr = new Doctor();
dr.setWard(5);
dr.setFirstName("ed");
dr.setLastName("fall");
System.out.println(dr.toString());
}
}
OUTPUT
Staffmember firstName=Steven, lastName=bob
Programmer firstName=Marion , lastName=bob language Java
default constructor
Doctor firstName=ed , lastName=fall Ward 5
Sorry guys here the class the default constructor is in. It is the Superclass called Staffmember and the firstname, lastname Strings are passed through it.
package oopinheritance;
public class Staffmember {
private String firstName;
private String lastName;
// default constructor
public Staffmember() {
System.out.println("default constructor");
}
// constructor
public Staffmember(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
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() {
return "Staffmember firstName="
+firstName+ ", lastName=" + lastName;
}
}
Here is the Doctor class, it is a subclass of Staffmember and it has its own tostring method:
package oopinheritance;
public class Doctor extends Staffmember{
private int ward;
public int getWard() {
return ward;
}
public void setWard(int ward) {
this.ward = ward;
}
public String toString() {
return "Doctor firstName="
+this.getFirstName() + " , lastName=" + this.getLastName() + " \t
ward" + this.ward;
}
}
As you have not shown your whole program, so its hard to tell where is the error, but it might be in the default constructor of the doctor class.
Anyways here is the code that you can refer. It will give the correct output.
Here is the link you can refer to see the execution order
http://javabeginnerstutorial.com/learn-by-example-3/order-of-execution-of-blocks-in-java/
Java Constructors - Order of execution in an inheritance hierarchy
class GfG {
public static void main(String[] args) {
Staffmember aStaffMember = new Staffmember("Steven", "bob");
System.out.println(aStaffMember.toString());
Programmer appleprg = new Programmer("Marion", "bob", "Java");
appleprg.getLanguage();
System.out.println(appleprg.toString());
Doctor dr = new Doctor();
dr.setWard(5);
dr.setFirstName("ed");
dr.setLastName("fall");
System.out.println(dr.toString());
}
}
class Staffmember {
String firstName;
String lastname;
public Staffmember(String firstName, String lastname) {
super();
this.firstName = firstName;
this.lastname = lastname;
}
#Override
public String toString() {
return "Staff Member firstName=" + firstName + ", lastname=" + lastname;
}
}
class Programmer {
String firstName;
String lastName;
String Language;
public String getLanguage() {
return Language;
}
public void setLanguage(String language) {
Language = language;
}
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 Programmer(String firstName, String lastname, String Language) {
super();
this.firstName = firstName;
this.lastName = lastname;
this.Language = Language;
}
#Override
public String toString() {
return "Programmer firstName=" + firstName + ", lastName=" + lastName + ", Language=" + Language;
}
}
class Doctor {
int ward;
String firstName;
String lastName;
public void setWard(int ward) {
this.ward = ward;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastname) {
this.lastName = lastname;
}
public Doctor(int ward, String firstName, String lastName) {
super();
this.ward = ward;
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return "Doctor ward=" + ward + ", firstName=" + firstName + ", lastName=" + lastName;
}
}

How i can bind two substring to one?

I have two string
private StringProperties firstName;
private StringProperties lastName;
private StringProperties nickName;
the first and last name are picked by user, the nickName is a concatenation of first 3 character of first and lastname
How i can do that?
Actually i initialize it like that (this is the entire class).
public class Person {
private StringProperty firstName;
private StringProperty lastName;
private StringProperty nickName;
private ObservableList<Evento> eventi = FXCollections.observableArrayList();
public Person(String firstName, String lastName) {
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
if (firstName.length() > 2 && lastName.length() > 2)
this.nickName = new SimpleStringProperty(firstName.trim().substring(0,3).concat(lastName.trim().substring(0,3)));
else
this.nickName = new SimpleStringProperty("");
}
public ObservableList<Evento> getEventi() {
return eventi;
}
public String getFirstName() {
if(firstName == null) firstName = new SimpleStringProperty(this,"firstName");
return firstName.get();
}
public StringProperty firstNameProperty() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public String getLastName() {
if(lastName == null) lastName = new SimpleStringProperty(this, "lastName");
return lastName.get();
}
public StringProperty lastNameProperty() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
public String getNickName() {
if(nickName == null) nickName = new SimpleStringProperty(this,"nickName");
return nickName.get();
}
public StringProperty nickNameProperty() {
return nickName;
}
#Override
public String toString() {
return getNickName() + "(" + getLastName() + " " + getFirstName() + ")";
}
}
but when i let the user change first or lastName, the nickName won't update.
You should use ReadOnlyStringProperty for the nickname:
private ReadOnlyStringWrapper nickName= new ReadOnlyStringWrapper();
...
public final String getNickName() {
return nickName.get();
}
public final ReadOnlyStringProperty nickNameProperty() {
return nickName.getReadOnlyProperty();
}
As for binding, you can use utility methods from Bindings class or implement your own binding for any other complicated cases. This example uses createStringBinding() method. It takes Callable functional interface, which will be used to calculate new value, and list of observable properties, which values will be observed for changes:
public Person(String firstName, String lastName) {
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
this.nickName.bind(Bindings.createStringBinding(()->{
if(this.firstName.get().length() > 2 && this.lastName.get().length() > 2) {
return this.firstName.get().substring(0,3).concat(this.lastName.get().trim().substring(0,3));
} else {
return "";
}
}, this.firstName, this.lastName));
}
You can use Bindings.format:
nickName.bind(Bindings.format("%.3s%.3s", firstName, lastName));
The 3 in %.3s is the maximum length of the string.
This won't do any trimming of the strings though, (you could do that before passing the strings to firstName and lastName).
It will also work on strings that are smaller than 3 characters. So, you can get nicknames like FoBar, FooB or Bar (if the first name is an empty string).

Constructor requiring more than one for subclass super

Please help me find errors from this code. I'm still new and I don't know if this is correct or not.
I do have one error.
This is the error:
constructor Person in class Person cannot be applied to given types;
super();
^
required: String,String,String
found: no arguments
reason: actual and formal argument lists differ in length
This is my code:
import java.util.*;
public class Person {
//Data fields
private String lastName;
private String middleInitial;
private String firstName;
//Constructors
public Person(String lastName, String middleInitial, String firstName) {
this.lastName = lastName;
this.middleInitial = middleInitial;
this.lastName = lastName;
}
//Accessor methods
public String getlastName() {
return lastName;
}
public String getmiddleInitial() {
return middleInitial;
}
public String getfirstName() {
return firstName;
}
//Mutator methods
public void setlastName(String lastName) {
lastName = lastName;
}
public void setmiddleInitial(String middleInitial) {
middleInitial = middleInitial;
}
public void setfirstName(String firstName) {
firstName = firstName;
}
public String getName() {
String studentName = this.lastName + ", " + this.firstName +
this.middleInitial + ".";
return studentName;
}
} //end Person class
class Address {
//Data fields
private String streetName;
private int zipCode;
private String state;
private String country;
//Constructors
public Address(String streetName, int zipCode, String state,
String country) {
this.streetName = streetName;
this.zipCode = zipCode;
this.state = state;
this.country = country;
}
//Accessor methods
public String getstreetName() {
return streetName;
}
public int getzipCode() {
return zipCode;
}
public String getstate() {
return state;
}
public String getcountry() {
return country;
}
//Mutator methods
public void setstreetName(String streetName) {
streetName = streetName;
}
public void setzipCode(int zipCode) {
zipCode = zipCode;
//Integer.toString(zipCode);
}
public void setstate(String state) {
state = state;
}
public void setcountry(String country) {
country = country;
}
public String getAddress() {
String studentAddress = streetName + "\n" + state + ", " + country +
"\n" + zipCode;
return studentAddress;
}
} //end Address class
class Student extends Person {
private String dateOfBirth;
//Constructors
public Student (String studentName, String dateOfBirth) {
super();
dateOfBirth = dateOfBirth;
}
//Accessor methods
public String getdateOfBirth() {
return dateOfBirth;
}
//Mutator methods
public void setdateOfBirth() {
this.dateOfBirth = dateOfBirth;
}
public String toString() {
return ("Date of Birth: " + dateOfBirth);
}
} //end Student subclass
Edited: If I do so for both the Person and Address class. I can only have three-arg constructors. How can I call a one-arg constructor?
For example, I have
public Student (String firstName, String lastName, String middleInitial, String dateOfBirth) {
super(firstName, lastName, middleInitial); and
public Student (String streetName, String state, String country) {
super(streetName, state, country);
How can I get zipcode separately?
Class Person has a constructor, therefore the default no-arg constructor is not created for you. Therefore you can't call super() in Student's constructor, you have to call super(lastName, middleInitial, firstName);.
Or you could create a new Person no-arg constuctor.
Try this
In student class
public Student ( String lastName, String middleInitial, String firstName,String studentName, String dateOfBirth) {
super( lastName, middleInitial,firstName);
this.dateOfBirth = dateOfBirth;
}
Or
In Person class create no arg consructor. Eg:
public Person(){}
Person Class has a constructor with arguments. So default constructor will not be created. So you have to pass 3 String parameters in super(3 String parameters) or you have to create a constructor which does not take any parameter in person class.

How to make constructor that takes in 2 if there are 2 parameters, or 3 if there are 3

New to Java...
I have a name class that has:
private String firstName;
private String middleInitial;
private String lastName;
as its instance variables.
If I had certain data that had only firstName and lastName, no middleInitial, how would I make the constructor so that it took only 2 parameters instead of three?
You simply write a constructor with two parameters and a constructor with three
public YourClass(String firstName, String lastName) {
...
}
public YourClass(String firstName, String middleInitial, String lastName) {
...
}
Callers can then choose to use the appropriate constructor based on their needs.
Well, two options:
Just have a constructor with three parameters, and call it using null or the empty string for middleInitial
Overload the constructors, possibly calling one from the other.
As an example for the latter, using an empty string as the default middle initial:
public Person(String firstName, String middleInitial, String lastName)
{
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = lastName;
}
public Person(String firstName, String lastName)
{
this(firstName, "", lastName);
}
However, the compiler will need to know which one you're calling from the call site. So you can do:
new Person("Jon", "L", "Skeet");
or
new Person("Jon", "Skeet");
... but you can't do:
// Invalid
new Person(firstName, gotMiddleInitial ? middleInitial : ???, lastName);
and expect the compiler to decide to use the "two name" variant instead.
In Java, constructors can't have default arguments. Your only option here is to write two constructors. Fortunately, Java does allow you to call constructors from other constructors. You could do something like:
public class MyClass {
private String firstName;
private String middleInitial;
private String lastName;
public MyClass(String firstName, String middleInitial, String lastName) {
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = lastName;
}
public MyClass(String firstName, String lastName) {
this(firstName, "", lastName);
}
...
}
public Class Name{
private String first;
private String middle;
private String last;
public Name(String first, String middle, String last){
this.first = first;
this.middle = middle;
this.last = last;
}
public Name(String first, String last){
this.first = first;
this.last = last;
}
}
You could use two constructors:
public Person(String firstName, String lastName)
{
this(firstName, null, lastName);
}
public Person(String firstName, String middleInitial, String lastName)
{
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = = lastName;
}
Define 2 constructors, one with 2 parameters and one with 3 parameters.
You can write two constructors.
public Person( String firstName, String lastName, String middleName ) { ... }
public Person( String firstName, String lastName ) { ... }
public void myBike(String name, String color)
{
System.out.println("My bike's name is " + name + " and is " + color + ".");
}
public void myBike(String name, String color, float height)
{
System.out.println("My bike's name is " + name + " and is " + color + ".");
System.out.println("My bike is also " + height + " inches tall.");
}
Builder pattern...
class Name {
Builder builder;
public String getSurname() {
return builder.surname;
}
// getter...
public Name(Builder builder) {
this.builder = builder;
}
class Builder {
String surname = "";
String middleName = "";
String name = "";
Builder surname(String surname) {
this.surname = surname;
return this;
}
Builder middleName(String middleName) {
this.middleName = middleName;
return this;
}
Builder name(String name) {
this.name = name;
return this;
}
Name build() {
return new Name(this);
}
}
}

Categories

Resources