Results 1 to 3 of 3

Thread: Java class

  1. #1
    unicorn is offline Member
    Join Date
    Oct 2009
    Posts
    9
    Rep Power
    0

    Default Java class

    Hello,
    I was taught to right a class with writing all accessor and mutator methods for all its attributes. But I remember sometime (also tested and this works) dot notation is used following its attribute to access it instead of using accessor method.

    For example:

    public class Person
    {
    private String name;
    private int age;
    }

    public Person()
    {
    name = "";
    age = 0;
    }

    public String getName()
    {
    return name;
    }

    public int getAge()
    {
    return age;
    }

    public void setName(String name)
    {
    this.name = name;

    public void setAge(int age)
    {
    this.age = age;
    }

    Person p1 = new Person();
    p1.setName("John Smith");
    p1.setAge(100);

    Now if I want to get p1's name, I can do either one:
    String oldMan = p1.name;
    oldMan = p1.getName();

    I don't know if there is any differences between these two methods to access an attribute of an object. I was taught to create and use accessor method instead of dot notation. But the dot notation is neat.

    This is really basic but sometime I forget.
    Thank you for your help.

  2. #2
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    11

    Default

    Since the fields are private, you can only do p1.name inside the same class file. If, however, you instantiated a Person in a class named "Main", then it would not work, because you wold be trying to access a private field from a different class (which is not allowed).

    For this reason, accessors / mutators are used as a way to keep the implementation separated from the interface. Additionally, if you had placed checks (e.g. age must be positive), you could either throw an exception or set a default value when someone called person.setAge(0). You cannot add such constraints on the statement person.age = 0;
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  3. #3
    unicorn is offline Member
    Join Date
    Oct 2009
    Posts
    9
    Rep Power
    0

    Default

    That makes sense now. I had everything in one file, that's why it works.
    Thanks

Similar Threads

  1. Replies: 1
    Last Post: 05-31-2009, 11:57 PM
  2. Replies: 1
    Last Post: 05-31-2009, 03:17 PM
  3. Replies: 16
    Last Post: 05-28-2009, 04:41 PM
  4. Replies: 14
    Last Post: 05-28-2009, 06:44 AM
  5. class.java to class.exe
    By f_the_cook in forum New To Java
    Replies: 11
    Last Post: 07-16-2008, 03:24 PM

Posting Permissions

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