The Artima Developer Community
Sponsored Link

Java Answers Forum
Help me better Understand?

1 reply on 1 page. Most recent reply: Oct 20, 2003 4:42 AM by Joe Parks

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Senthoorkumaran Punniamoorthy

Posts: 335
Nickname: senthoor
Registered: Mar, 2002

Help me better Understand? Posted: Oct 20, 2003 12:55 AM
Reply to this message Reply
Advertisement
class Parent {
  public void print() {
    System.out.println("Parent");
  }
}
 
public class Child extends Parent {
 
  public void col() {
    System.out.println("Test");
  }
 
  public static void main(String args[]) {
    Parent n = new Child();
    n.col();
  }
}


I know the above code will not compile!!! But when I was going through the book The Java Programming Language by Games Gosling it states at page 75

When you invoke a method through an object reference, the actual class of the object governs which implementation is used. When you access a field, the declared type of the reference is used.

Therefore in this case the variable n actual class is Child and the declared type of the reference is Parent. Which means that when invoking the method col() the actual class of the Object Governs which implementation is used!!!

Then why the code doesn't compile and always looks for col() method implantation in the Parent class???


Joe Parks

Posts: 107
Nickname: joeparks
Registered: Aug, 2003

Re: Help me better Understand? Posted: Oct 20, 2003 4:42 AM
Reply to this message Reply
> When you invoke a method through an object reference,
> the actual class of the object governs which
> implementation is used.


This implies that the reference type and the actual class share the same public interface, but differ in implementation.

If you were to add an overriding "print" method to your Child class,
public void print() {
    System.out.println("Child");
}

Then you could see the point of this section of the spec:
public static void main(String [] args) {
    Parent grandparent = new Parent();
    grandparent.print(); // will print "Parent"
    Parent parent = new Child();
    parent.print(); // will print "Child"
}


Because (in this example) parent is declared as type "Parent", you cannot invoke methods on it that do not exist in the Parent public interface without casting it.
    (Child)parent.col();

Flat View: This topic has 1 reply on 1 page
Topic: Font property in JTable Previous Topic   Next Topic Topic: a part of the code JList

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use