Results 1 to 20 of 20

Thread: Accessor method

  1. #1
    DC200 is offline Member
    Join Date
    Dec 2008
    Posts
    49
    Rep Power
    0

    Default Accessor method

    I'm having trouble accessing an object. Here's some of my code...

    Java Code:
    public class Student{
    	public Student(int h, int a, int i, String n) {
    		height=h;
    		age=a;
    		iq=i;
    		name=n;
    	}
    
    	public String getName() {
    		return name;
    	}
    }
    The accessor method in my Student class works fine when used on an object that has a name. For example...

    Java Code:
    Student studentA = new Student(172,22,110,"gary");
    System.out.println(studentA.getName());
    However when I create an object that doesn't have a name, how am I supposed to use the accessor method on it?

    Java Code:
    new Student(182,18,122,"gary");
    System.out.println(???.getName());
    The reason I'm creating objects without name is because I've written a program that creates student objects based on input from a scanner class. I don't know if it's possible to name objects using input from a scanner.
    Last edited by DC200; 06-12-2009 at 05:43 AM.

  2. #2
    JohnnyR is offline Member
    Join Date
    Feb 2009
    Posts
    46
    Rep Power
    0

    Default

    Well, Technically your name is just an attribute.
    Your objects reference point is studentA

    You can either have another constructor in Student that accepts the same parameters with out a name or just have

    Student studentB = new Student(182,18,122,"");
    then use your normal studentB.getName();

    your second section of code makes no sense as its not creating anything and it also has the name "gary" being assigned.

    Java Code:
    public class Student{
    	public Student(int h, int a, int i, String n) {
    		height=h;
    		age=a;
    		iq=i;
    		name=n;
    	}
          	public Student(int h, int a, int i) {
    		height=h;
    		age=a;
    		iq=i;
    	}
    
    	public String getName() {
    		return name;
    	}
    }
    Using this will allow you to create a student object with out a name (however assuming you havn't initialised it it will return null if you try and call it or nothing).

    Student studentC = new Student(182,18,122);
    studentC.getName() = null or "" can't remember
    Last edited by JohnnyR; 06-12-2009 at 06:12 AM.

  3. #3
    DC200 is offline Member
    Join Date
    Dec 2008
    Posts
    49
    Rep Power
    0

    Default

    Yes, but how do I use the getName() method on an object whose reference point is unknown to me? Take the following object, for example.

    Java Code:
    new Student(182,18,122,"gary");
    What is its reference point?
    Last edited by DC200; 06-12-2009 at 07:05 AM.

  4. #4
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default Objects withod assigned variables cannot be accessed

    Quote Originally Posted by DC200 View Post
    What is its reference point?
    There is no reference point. It cannot be accessed, because there is no variable assigned to it.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  5. #5
    DC200 is offline Member
    Join Date
    Dec 2008
    Posts
    49
    Rep Power
    0

    Default

    Ah, I see.

    How else can I create an object during runtime? Obviously I can't hardcode the reference points because the number of objects is indefinite.

    Object objectname = new Object(parameters);

    In this case, objectname would be some sort of a variable that allows me to assign new reference points to each new objects.
    Last edited by DC200; 06-12-2009 at 06:53 AM.

  6. #6
    JohnnyR is offline Member
    Join Date
    Feb 2009
    Posts
    46
    Rep Power
    0

    Default

    Every object has to have a reference point.

    You just want to create some with names and some with out which is where my above stuff comes in.

    You could store them in an ArrayList or predefined Object[].

    Then you can loop through that to pull them out, you can't just create an object over and over with the same variable reference, they need to be stored somewhere, cause otherwise it overrides the previous pointer to the previous object.

    make sense?

    e.g. you loop over
    int i = 0;
    while (i != 5) {
    Object objectname = new Object();
    i++;
    }

    This creates an object of reference of objectname 5 times, but only the 5th object is actually still available as its the only one left with a reference point of object name.

    You want to add an ArrayList in there to list.add(objectname) once its completed and then you will see 5 objects with in that list all with pointers to each object.

  7. #7
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Quote Originally Posted by JohnnyR View Post
    What he said :)
    No need for posts like that...

    Just thought of a quick correction... objects created without assigning a variable to them cannot be accessed in the constructor/method they are created by. However, if you create them as constructor/method parameters they can be accessed by the constructor/method they are parameters for.

    e.g
    Java Code:
    public boolean testEquality(JLabel labs){//Allows unlimited JLabel parameters
         JLabel firstLab = labs[0];//gets a single JLabel from the array to test against
         for(JLabel lab : labs){
              if(!lab.equals(firstLab)){
                   return false;
              }
         }
         return true;
    }
    
    public boolean callEqualityMethod(){
         return testEquality(new JLabel("text"), new JLabel("anotherText"), new JLabel());
    }
    The method callEqualityMethod will always return false. TestEquality probably would always return false as well, because I don't believe JLabel overrides .equals. But that is irrelevant. The point is that objects created using new MyObject() without assigning a variable are only accessible if used as parameters, and even then can only be accessed by the constructor/method they are parameters for.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  8. #8
    DC200 is offline Member
    Join Date
    Dec 2008
    Posts
    49
    Rep Power
    0

    Default

    Thank you both for offering alternatives, but I still don't think either of you understand what I'm trying to do. I'm probably not being concise enough, and I apologize for that.

    What I'm trying to do is allow the user to create as many objects as they want during runtime. Leaving out the object's reference point was one way I thought this could be done, though I now understand that this was the wrong approach since it makes it difficult to access the objects after they have been created.

    I'm hoping that there is another simple way I could go about doing this.
    Last edited by DC200; 06-12-2009 at 07:17 AM.

  9. #9
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Hmm... What you want is a dynamic array... Try using an ArrayList or Vector. They both allow you to add, remove, and get objects. The only real difference is that ArrayList is unsynchronized, while Vector is. I would suggest that you use an ArrayList, because I doubt that you will be doing multi-threaded programming with multiple threads accessing the ArrayList, and a Vector takes far more memory than an ArrayList.
    Take this method...
    Java Code:
    public String[] getAnArray() throws IOException{
         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
         ArrayList<String> strings = new ArrayList<String>();
         String input;
         while(true){
              System.out.println("Enter a string or press enter to indicate completion.");
              input = reader.readLine();
              if(input.equals(""))
                   break;
              strings.add(input);
         }
         return strings.toArray(new String[0]);
    }
    The code above allows the user to enter an undefined number of Strings, adds them to the ArrayList, and if they press enter, it returns the ArrayList as a String array by calling toArray.

    Hope this is what you were looking for,
    Singing Boyo
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  10. #10
    DC200 is offline Member
    Join Date
    Dec 2008
    Posts
    49
    Rep Power
    0

    Default

    Yes, I'm already using an ArrayList. This is what I've got so far...

    Java Code:
    import java.util.*;
    
    public class StudentArray{
    	public static void main (String[] args){
    
    	//create arraylist
    	ArrayList<Object> studentArray = new ArrayList<Object>();
    
    	//input loop 
    	while(1==1) {
    		Scanner input = new Scanner(System.in);
    		System.out.println("continue? y/n");
    		String cont = input.nextLine();
    			
    		if (cont.equals("n")) {
    			break;
    		}
    			
    		else {
    			System.out.print("\nstudent name: ");
    			String name = input.nextLine();
    
    			System.out.print("height: ");
    			int height = input.nextInt();
    
    			System.out.print("age: ");
    			int age = input.nextInt();
    
    			System.out.print("iq: ");
    			int iq = input.nextInt();
    				
    			studentArray.add(new Student(height,age,iq,name));
    		}
    	}
    
    	//iterator interface
    	Iterator itr = studentArray.iterator();
    	while (itr.hasNext())	{
    		System.out.println(itr.next());
    		//System.out.println(itr.next().getName()); //does not work (symbol not found error thrown by compiler)
    	}
    
    	}
    }
    It uses the same Student class from my first post in this thread. Now suppose I run the program and loop twice to create two Student objects, this is what System.out.println(itr.next()); will display:

    Java Code:
    Student@14318bb
    Student@ca0b6
    In the end, I can create as many objects as I want and store them into the ArrayList, but the problem is that I cannot use my getName() method on said objects since they do not have reference points.
    Last edited by DC200; 06-12-2009 at 08:37 AM.

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    but they do. You can access them through the arraylist of course.

    The reason for the funny results in your println is that you haven't given the objects a toString() method override, and so Java just ouputs the default toString() result. I'd give student a String name field (I didn't see one declared in your code above), and then create a method like so:
    Java Code:
    public String toString() {
      return name;
    }
    Also, please don't cripple your ArrayList by making it an array list of object: ArrayList<Object>. it's not. It's an ArrayList<Student>

  12. #12
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,931
    Rep Power
    19

    Default

    As Fubarable says this:

    Java Code:
    ArrayList<Object> studentArray = new ArrayList<Object>();
    should be this:

    Java Code:
    ArrayList<Student> studentArray = new ArrayList<Student>();
    because that's what it is. Which then allows you to turn your Iterator into an Iterator<Student>. Which means the line you commented out:

    Java Code:
    System.out.println(itr.next().getName());
    will now work.

  13. #13
    DC200 is offline Member
    Join Date
    Dec 2008
    Posts
    49
    Rep Power
    0

    Default

    I did what Fubarable told me to do, and it seems to be working perfectly now. It turns out that all I needed was a toString() method override to replace my getName() method.

    Now, itr.next() can display the names of each Student object.

    Thanks. :)
    Last edited by DC200; 06-12-2009 at 08:21 PM.

  14. #14
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,931
    Rep Power
    19

    Default

    Quote Originally Posted by DC200 View Post
    I did what Fubarable told me to do, and it seems to be working perfectly now. It turns out that all I needed was a toString() method override to replace my getName() method.

    Now, itr.next() can display the names of each Student object.

    Thanks. :)
    Well, I hate to say it, but that's not a proper solution. I'm assuming you're still using an ArrayList<Object>, rather than an ArrayList<Student>, which is bad practice. In addition, writing a toString() whose job is, in fact, a getName(), is also bad. Someone using your code (and I realise this is not something likely to see the light of day past your course) will not expect toString() to only supply the name. I would expect it to provide a full description of the object (ie all the data in Student).

    A proper solution is the one I proposed above (and pointed out by Fubarable originally). Anything else is merely putting sticky tape over a problem,which is never a good thing.

  15. #15
    DC200 is offline Member
    Join Date
    Dec 2008
    Posts
    49
    Rep Power
    0

    Default

    I understand what you're trying to say. I have to admit that I didn't understand what was causing this problem, and so I didn't realize that I was merely covering up the flaws in my program. I did follow your advice as well and changed the ArrayList<Object> to an ArrayList<Student>, but even then I was having trouble getting the commented line to compile.

  16. #16
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,931
    Rep Power
    19

    Default

    Quote Originally Posted by DC200 View Post
    I understand what you're trying to say. I have to admit that I didn't understand what was causing this problem, and so I didn't realize that I was merely covering up the flaws in my program. I did follow your advice as well and changed the ArrayList<Object> to an ArrayList<Student>, but even then I was having trouble getting the commented line to compile.
    You're learning, so there's no problem there. Did you change the Iterator to an Iterator<Student>? If it's still a straight Iterator then that's the equivalent to Iterator<Object>, which means that you will still have that problem.

    If you have changed it to <Student> then if you post the code (and the compilation error) we might be able to spot the problem.

  17. #17
    DC200 is offline Member
    Join Date
    Dec 2008
    Posts
    49
    Rep Power
    0

    Default

    Oh, I didn't know I was supposed to change the iterator to <Student> as well. I did that, and now it's giving me a compilation error. Below is the iterator section of my code. I posted the rest earlier (see post #10).

    Java Code:
    	//iterator interface
    	System.out.println("\niterating through array...");
    	Iterator<Student> itr = studentArray.iterator();
    	while (itr.hasNext())	{
    		System.out.println(itr.next());
    	}
    Java Code:
    StudentArray.java: incompatible types
    found: java.util.Iterator<java.lang.Object>
    required: java.util.Iterator<Student>
         Iterator<Student> itr = studentArray.iterator();
    Perhaps I'm not instantiating the iterator properly.
    Last edited by DC200; 06-16-2009 at 05:46 PM.

  18. #18
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,931
    Rep Power
    19

    Default

    Quote Originally Posted by DC200 View Post
    Oh, I didn't know I was supposed to change the iterator to <Student> as well. I did that, and now it's giving me a compilation error. Below is the iterator section of my code. I posted the rest earlier (see post #10).

    Java Code:
    	//iterator interface
    	System.out.println("\niterating through array...");
    	Iterator<Student> itr = studentArray.iterator();
    	while (itr.hasNext())	{
    		System.out.println(itr.next());
    	}
    Java Code:
    StudentArray.java: incompatible types
    found: java.util.Iterator<java.lang.Object>
    required: java.util.Iterator<Student>
         Iterator<Student> itr = studentArray.iterator();
    Perhaps I'm not instantiating the iterator properly.
    If you're still using the code in post 10 then this:

    Java Code:
    ArrayList<Object> studentArray = new ArrayList<Object>();
    is your problem. Your Iterator<Student> is fine, however studentArray is not an ArrayList<Student>. You have to have both...the type if the iterator has to match the type of the list.

    Edit: Also, you really ought to be doing itr.next().getName() in the println.
    Last edited by Tolls; 06-16-2009 at 05:55 PM.

  19. #19
    DC200 is offline Member
    Join Date
    Dec 2008
    Posts
    49
    Rep Power
    0

    Default

    I was just about to post the code again when I noticed that my ArrayList hadn't been changed to <Student>. I could have sworn that I had already done that earlier...

    Anyway, it seems to be working perfectly now. I also noticed that after changing the ArrayList and Iterator to <Student>, I can use my getName() method on the objects without the need for a toString() override. Spot on.

    Thank you for taking the time to point this out. :)
    Last edited by DC200; 06-17-2009 at 02:39 AM.

  20. #20
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,931
    Rep Power
    19

    Default

    Quote Originally Posted by DC200 View Post
    I was just about to post the code again when I noticed that my ArrayList hadn't been changed to <Student>. I could have sworn that I had already done that earlier...

    Anyway, it seems to be working perfectly now. I also noticed that after changing the ArrayList and Iterator to <Student>, I can use my getName() method on the objects without the need for a toString() override. Spot on.

    Thank you for taking the time to point this out. :)
    The getName() works because the compiler now knows that, firstly everything in your ArrayList is a Student, and secondly everything returned by your Iterator is also a Student. This means that itr.next() actually returns a Student and not simply an Object as it was doing before.

Similar Threads

  1. Replies: 2
    Last Post: 03-26-2010, 05:12 PM
  2. Accessor help needed (I think...- little confussed)
    By thomase in forum New To Java
    Replies: 7
    Last Post: 03-11-2009, 10:29 AM
  3. Replies: 6
    Last Post: 12-02-2008, 11:15 PM
  4. Replies: 29
    Last Post: 09-25-2008, 07:55 PM
  5. cannot call private method from static method
    By jon80 in forum New To Java
    Replies: 3
    Last Post: 05-07-2008, 08:37 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •