Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: methods are checked based on the reference, not the object. why?

  1. #1
    Junior Member
    Join Date
    Jun 2014
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default methods are checked based on the reference, not the object. why?

    Check out the following basic code (assume that dog has a method called bark):

    Dog d = new Dog();  
    Object o = d;  
     
    o.bark();  //  error


    But why? Isn't o just a pointer to a memory address which has the dog object? If so, why can't the compiler see that the object has a method called bark? Or, to ask the question another way, why is Java designed to check the object reference to see if the method exists instead of the object itself?


  2. #2
    Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    398
    Thanks
    0
    Thanked 67 Times in 56 Posts

    Default Re: methods are checked based on the reference, not the object. why?

    o is a Variable which references an Object.
    Objects do not have a method called bark; thus you cant call the bark method on an object variable.

    You know that the object is actually a Dog, but your compiler cant know that. Since the compiler doesnt know he wont compile it.

Similar Threads

  1. Can an object change it's own reference?
    By Cereno in forum Java Theory & Questions
    Replies: 3
    Last Post: December 5th, 2012, 12:29 PM
  2. Object Reference
    By Mr.777 in forum Object Oriented Programming
    Replies: 2
    Last Post: June 13th, 2011, 03:03 AM
  3. Passing reference via object
    By Stefan_Lam in forum Java Theory & Questions
    Replies: 1
    Last Post: January 7th, 2011, 10:57 AM
  4. Object as a Reference into Object's Class
    By Ace Coder in forum Object Oriented Programming
    Replies: 6
    Last Post: November 30th, 2010, 11:22 AM
  5. Object as Reference not working
    By jassi in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 9th, 2010, 08:47 AM