1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

What is Instance, Empty Constructor in Java

  1. Oct 23, 2009 #1
    What is Instance, Empty Constructor .... in Java

    How come will return false I put in 2 same name it should return true ?

    Code (Text):
    Teacher p1= new Teacher("Nelson");
    System.out.println(p1);
    Teacher p2= new Teacher("Nelson");
    System.out.println(p2);

    System.out.println(p1.equals(p2));
    it print out
    Code (Text):
    false

    I do testing on below it give me ture how come the above not give me true

    Code (Text):
    p1 = "Nelson";
    p2 = "Nelson";
    System.out.println(p1.equals(p2));
     
    Last edited: Oct 23, 2009
  2. jcsd
  3. Oct 24, 2009 #2
    Re: What is Instance, Empty Constructor .... in Java

    Without knowing much about Java (i.e. I could be wrong):

    The equals method probably has a default implementation that just compares the two pointers and returns true or false depending on it.

    so:

    Code (Text):

    Teacher p1= new Teacher("Nelson");
    System.out.println(p1);
    Teacher p2= new Teacher("Nelson");
    System.out.println(p2);
     
    p1.equals(p2)

    actually calls (say)

    Code (Text):

    bool object.equals(object p2)
    {
      return p2==this;
    }
     
    Whereas... in your second example you had strings and string will have a specific equals method that compares strings as you expect.

    So... write an equals that overrides the default one.
     
  4. Oct 24, 2009 #3
    Re: What is Instance, Empty Constructor .... in Java

    K I did something like this and all ok now it return the true compare value

    Code (Text):

    public boolean equals(Object o)
    {
    System.out.println(o instanceof Moof);
    System.out.println(((Moof)o).getMoofValue());
    System.out.println(this.moofValue); //XXX
    if ((o instanceof Moof) && (((Moof)o).getMoofValue() == this.moofValue))
    {
    return true;
    }
    else
    {
    return false;
    }
     
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: What is Instance, Empty Constructor in Java
Loading...