An exercise about Java constructors

127 Views Asked by At

I have an exercise which is asking us about basics concept apparently. But I can't find any information or at least I'm not sure about what I'm suppose to search. So I have a small class and I need to comment 3 different constructors. It look like this :

class Person{
      private String name;
      private ArrayList<String> pseudos;
      private String email;

//For me this one isn't a problem, it initialize a name & a mail with the two parameters and I believe the tricky part is this Array. I'm not sure but as far as I know it's okay to initialize the Array whithout getting him through parameter... Maybe I'm wrong.
public Person(String aName, String aEmail){
       name = aName;
       pseudos = new ArrayList<String>();
       email = aMail;
}

//It seems to be the same explanation than the first one.
public Person(){
       pseudos = newArrayList<String>();
}

//Apart from the uppercase I thinks this one is good, nothing is wrong.
public Person(String aName, String aMail, ArrayList<String> manyPseudos){
       name = aName;
       pseudos = new ArrayList<String>();
       if(pseudos != null)
       {
            Pseudos.addAll(manyPseudos); //The uppercase here should be the problem
       }
       mail = aMail;
  }
}

Of course I tried to figured it out through my lesson, but I didn't find anything so i supposed it's an exercise based on logic ... But I lacked of this kind of logic and I really want to at least trully understand this part since it's pretty basics and I will have to manipulate it a lot.

Again, thanks for your guidance and your time.

1

There are 1 best solutions below

3
Code-Apprentice On

I believe the tricky part is this Array. I'm not sure but as far as I know it's okay to initialize the Array whithout getting him through parameter... Maybe I'm wrong.

First, pseudos is an ArrayList, not an array. These are two different things.

Second, pseudos is a variable just like any other. This means you can initialize it in all the same ways you initialize any variable: from the value of another variable or directly from an expression. Here we initialize pseudos by creating a new ArrayList directly.

Pseudos.addAll(manyPseudos); //The uppercase here should be the problem

You have a good eye here. Psuedos at the beginning should be pseudos instead. Since Java is case-sensitive, these are two different things. We generally use the convention that class names start with uppercase and variables and functions start with lowercase. In theory you can have a class named Psuedos and a variable named pseudos, but you have to keep them separate in your mind.