Constructor undefined issue - java

public class Person {
public String Person(String name) {
return name;
}
public static void main(String[] args) {
Person one = new Person("hendry");
}
}
What am I doing wrong?

This is not a constructor, because you have declared a return type. It's just a method that happens to have the same name as your class.
public String Person(String name) {
Without an explicit constructor, the compiler inserts an implicit default constructor with no parameters, so there is a conflict with the number of arguments.
Remove the return type; no return type should be specified on constructors, not even void:
public Person(String name)
Don't return anything from the constructor. But, you may wish to store the parameter in an instance variable, and you may wish to add a method that returns that instance variable (a "getter").

Constructors don't have a return type. Why? Because their purpose of existing is to initialize attributes.
Maybe what you are looking for is a getter method:
public String getPerson(String name) {
return name;
}
But if you want it as constructor, to initialize an attribute, first declare it, and then assign the parameter of the constructor to it:
public class Person {
private String name;
public String Person(String pName) {
this.name = pName;
}
...
}

public String Person(String) is not valid constructor as constructors dont have return type. So actually as per compiler there is no parameterized constructor in your code but you are trying to call one

Constructor returns nothing. They can take parameter but they don't return anything.
It must be like this:
private String name;
public Person(String name) {
this.name = name; }
public String getName(){
return this.name; }
public static void main(String[] args) {
Person one = new Person("hendry");
String name = one.getName();
}

Related

How to cast in the compareTo method to a Generic Class which Implements Comparable?

I have an Arraylist with type Person. Name is a class that I have created. In my mainapp I'm creating some Name objects, setting each name-object to a person object and then adding the person objects to an ArrayList. When I try to sort the list using Collections.sort(), I get a ClassCastException.
I can not see what the problem is.
Here is my code so far:
public class Person<T> implements Comparable<Person<T>> {
private T name;
public T getName() {
return name;
}
public void setName(T name) {
this.name = name;
}
#Override
public int compareTo(Person<T> o) {
return ((Person<T>) this.getName()).compareTo((Person<T>) o.getName());
}
}
The return value from getName() has type T, but you are trying to cast it to Person<T>. To fix the problem, you need to compare the names directly without casting:
public int compareTo(Person<T> o) {
return this.getName().compareTo(o.getName());
}
Now this will cause another error because the compiler doesn't know if T has the compareTo() method. To fix that, you need to add a bound to the type T:
public class Person<T implements Comparable<T>> implements Comparable<Person<T>>
Note:
To me, this seems like overuse of generics. Why should name be allowed a generic type when String is the only natural fit? And why do you need a Name class? It is likely only a wrapper around a String so you should just use String directly.
You are casting this.getName(), which is of type T, to type Person<T>. I.e. you are casting a Name to a Person, hence the ClassCastException ("name is not a person").
To fix this, please remove the casts and compare the names directly. Ignoring null-safety, it would be:
return getName().compareTo(o.getName());
Note that class Name also needs to implements Comparable<Name>.
Why is your name a type? This looks a bit weird. Could it be you meant to do something like this:
public class Person implements Comparable<Person> {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int compareTo(Person other) {
return this.name.compareTo(other.getName());
}
}

I am trying to print the name of the list but somehow the reference from the arraylist is not working?

Customer is a class. The Class list is arraylist of Customer.
I have added the Customers to list but when I want to print all the customer names from the list I get null only.
import java.util.*;
public class Assignment1 {
public static void main(String args[])
{
List list = new List();
list.addCustomer("man");
list.addCustomer("man");
//System.out.println(list);
list.printx();
}
}
class Customer{
public String name;
public Customer(String name)
{
name = this.name;
}
}
class List
{
ArrayList<Customer> list = new ArrayList<Customer>();
public void addCustomer(String name1)
{
Customer x = new Customer(name1);
list.add(x);
System.out.println(list.get(0));
}
public void printx()
{
for(int i =0;i < list.size();i++)
{
System.out.println(list.get(i).name);
}
}
}
Inside your Customer constructor, you need to set ::
this.name = name;
and not the other way round! :P
What you have done right now is that you change the function parameter name to the class parameter name which is currently null(default initialization). So, you never initialize name variable of the Customer class, and hence you always get null when you print it.
I suggest you override the toString method in class Customer, it helps you debug your Customer objects. For example, you can change the local variable to assignedName as below:
class Customer{
public String name;
public Customer(String name)
{
this.name = name;
}
#Override
public String toString(){
return "customer name:" + this.name;
}
}
this.name and name are different things in the Customer constructor:
this.name is an instance variable and name is a local variable defined in your constructor.
// you should narrow the modifier to private, and implement getter and setter for it
public String name;
public Customer(String assignedName){
this.name = assignedName;
}

How to create get and set methods for parameters in a class? [duplicate]

This question already has answers here:
How do getters and setters work?
(6 answers)
Closed 7 years ago.
I have a class I created.
public class mailCustomer {
public static void main(String[] args) {
String Name;
int Id;
String Address;
Boolean IsPack;
}
}
I need to creat get and set methods for my parametrs, Name, Id,Address, IsPack.
how do I do that, and where do I write them? after the "main" method? in the "main" method?
Firstly, you need to declare the variables at the class level so that they can be used from anywhere within the class. Then after that you simply create a set and get method for each variable, like so
public class MailCustomer {
String name;
int id;
String address;
boolean isPack;
public static void main(String[] args) {
}
public void setName(String name) {
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public void setAddress(String address) {
this.address = address;
}
public void setIsPack(boolean isPack) {
this.isPack = ispack;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public String getAddress() {
return address;
}
public boolean getIsPack() {
return isPack;
}
}
It also appears that you have your naming conventions a little mixed up. In java, class names are capitalized, whereas variable and method names are camelCased
First, delete the main method from there. You are creating a class called mailCustomer that will create you object type of mailCustomer.
For this, you need three things: attributes (you have them there), a constructor and get/set methods. I will show you with a example, and you can guide from there. My class will be 'Rabbit' and it will have:
Attributes
-String eyes: Eye colour.
-String race: Where is it from.
Constructor
It will have one constructor, that will use both parameters.
Methods
It will have two getters and two setters, both for each attribute.
Here's my code for this class:
public class Rabbit{
//Attributes
private String eyes;
private String race;
//Constructor
public Rabbit(String colour, String where){
this.eyes = colour;
this.race = where;
}
//Methods get/set
public String getEyes(){
return this.eyes;
}
public String getRace(){
return this.race;
}
public void setEyes(String colour){
this.eyes = colour;
}
public void setRace(String where){
this.race = where;
}
}
As you can see, you will use get methods to return an specific attribute from the class; and set methods will be used if you want to change one of the attributes from a created object (in my case, from a created 'Rabbit').
Later, if you want to make use of this class, you will create your Main class, into the same package where 'Rabbit' class is created.
package rabbit;
public static void main(String[] args){
Rabbit George = new Rabbit("brown","spanish");
}
Now try to do this with your class. I hope it helped you!
public static void main(String[] args) {
String Name;
int Id;
String Address;
Boolean IsPack;
}
You can't create getters and setters for these, since they are not created in your class, but locally in your main method. What you want is:
public class MyClass{
String Name;
int Id;
String Address;
Boolean IsPack;
// getter for Name
public String getName(){
return this.Name;
}
// setter for Name
public void setName(String name){
this.Name = name;
}
public static void main(String[] args) {
}
}
For these you'll be able to create getters and setters.
It's (most likely) best to declare them private, though.
Also: following naming conventions could help other people easier read your code. Name (with capital N) is more suited as name of a class, while name (lowercase n) is the name of a variable.
As already said it seems that you are not familiar with Object Oriented Programming. It does not care. I just want to say that you can save a lot of time and improve your classes readability using lombok to automatically generate your getters and setters using annotations. You can find an example here : LOMBOK

Java Enum Constructor Undefined

Why am i getting an error "Constructor is undefined" is it in my eclipse IDE?
is there something wrong with my code?
public enum EnumHSClass {
PALADIN ("Paladin"),ROUGE("ROUGE");
}
If you expect your enums to have parameters, you need to declare a constructor and fields for those parameters.
public enum EnumHSClass {
PALADIN ("Paladin"),ROUGE("ROUGE");
private final String name;
private EnumHSClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
You need to provide a constructor in your enum like:
public enum EnumHSClass {
PALADIN("Paladin"), ROUGE("ROUGE");
String value;
EnumHSClass(String value) {
this.value = value;
}
}
Note: The constructor for an enum type must be package-private or
private access. It automatically creates the constants that are
defined at the beginning of the enum body. You cannot invoke an enum
constructor yourself.
Ref : http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
Enums have constructors too, but only with either private or default visibility:
public enum EnumHSClass {
PALADIN ("Paladin"),ROUGE("ROUGE");
private EnumHSClass(String s) {
// do something with s
}
}
You may want to declare a field and create a getter for it, and set the field in the constructor.
Also note that the name of the enum instance is available for free via the (implicit) name() method that all enums have - maybe you can use that instead.
Your code should look like this:
public enum EnumHSClass {
PALADIN ("Paladin"), ROUGE("ROUGE");
private String name;
private EnumHSClass(String name) {
this.name = name;
}
}
public enum Days {
MONDAY(1), TUESDAY(2);
int val;
Days (int val) {
this.val = val;
}
}

Java - Using Accessor and Mutator methods

I am working on a homework assignment. I am confused on how it should be done.
The question is:
Create a class called IDCard that contains a person's name, ID number,
and the name of a file containing the person's photogrpah. Write
accessor and mutator methods for each of these fields. Add the
following two overloaded constructors to the class:
public IDCard() public IDCard(String n, int ID, String filename)
Test your program by creating different ojbects using these two
constructors and printing out their values on the console using the
accessor and mutator methods.
I have re-written this so far:
public class IDCard {
String Name, FileName;
int ID;
public static void main(String[] args) {
}
public IDCard()
{
this.Name = getName();
this.FileName = getFileName();
this.ID = getID();
}
public IDCard(String n, int ID, String filename)
{
}
public String getName()
{
return "Jack Smith";
}
public String getFileName()
{
return "Jack.jpg";
}
public int getID()
{
return 555;
}
}
Let's go over the basics:
"Accessor" and "Mutator" are just fancy names fot a getter and a setter.
A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless.
B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables
public class IDCard {
public String name, fileName;
public int id;
public IDCard(final String name, final String fileName, final int id) {
this.name = name;
this.fileName = fileName
this.id = id;
}
public String getName() {
return name;
}
}
You can the create an IDCard and use the accessor like this:
final IDCard card = new IDCard();
card.getName();
Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.
If you use the static keyword then those variables are common across every instance of IDCard.
A couple of things to bear in mind:
don't add useless comments - they add code clutter and nothing else.
conform to naming conventions, use lower case of variable names - name not Name.

Categories

Resources