Question:
Java String int public constructor help?
rebeccakjoyce
2009-04-02 09:43:00 UTC
This is my assignment:
The code below shows some of the text for a class called City. Now write a complete public constructor, which takes a String parameter called cityName. Your code should initialize the name attribute of the City class to the value of cityName. It should initialize the population attribute to a value of -1.

This is my answer:
public class City {
private String name;
private int population;
public City(int p, String n){
population = p;
name = n;
}
public City(){
population = -1;
name = "cityName";
}
public String cityName(){
return name;
}
}

This is my error:
City() is already defined in constructors.City


Any ideas what I should do?
Three answers:
Karen M
2009-04-02 10:06:09 UTC
Looking at your instructions, your constructor should have a string parameter (making it an overloaded constructor). It would look like this:



public City (string cityName){

name = cityName;

population=-1;

}



Then you can remove the function cityName.



This constructor would be called if a new object is created with a specific string like this:

City myCity = new City("New York");
vereen
2016-12-02 12:02:10 UTC
** Constructor for passing preliminary fee for year field of sophistication pupil */ public pupil() it truly is what you have for a constructor (see no parameters) and once you create an merchandise pupil s = new pupil("Bert", 2, "555-5555"); You bypass bert and different parameters to the constructor, it has to tournament signitures interior the announcement of the constructor technique and implementation
modulo_function
2009-04-02 09:53:07 UTC
I don't see why there's a problem:it looks OK to me!


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...