The Artima Developer Community
Sponsored Link

Java Answers Forum
If class Y extends class X, the two classes are in different packages...

0 replies on 1 page.

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 0 replies on 1 page
mhukkll none

Posts: 1
Nickname: fmarek
Registered: Feb, 2008

If class Y extends class X, the two classes are in different packages... Posted: Feb 11, 2008 7:21 AM
Reply to this message Reply
Advertisement
I'm bit confusing answering tricky question:

True or false:
If class Y extends class X, the two classes are in different packages, and class X has a protected method called abby(), then any instance of Y may call the abby() method of any other instance of Y.
Correct answer is FALSE, but javac (1.4, 5, 6..) compiler successfully compiles classes of test program.


I'll be very thankful if you could provide me some hints why this is hapenning, why compiler produces no error? My first answer for the question was FALSE, but when I tried to check it, I found myself in strange situation being unable to understand what is wrong :) Please help me.


Program output:
y.Child[1] calling doit() using reference to y.Child[2]
protected method y.Child.doit() is called from class in package y
y.Child[1] calling doit() using reference to y.Child[1]
protected method y.Child.doit() is called from class in package y

Here is source code for test program.

public class InherintanceTest {
public static void main(String[] args) {
y.Child y1 = new y.Child();
y.Child y2 = new y.Child();
y1.callDoit(y2);
y1.makeSelfCall();
}
}




package y;

public class Child extends x.Base {
private static int i;
private int getint() {
return ++i;
}
private int name;
public Child() {
name = getint();
}
public void callDoit(Child obj) {
System.out.println(toString() + " calling doit() using reference to " + obj);
obj.doit(); // EXPECTING COMPILER ERROR, BUT NO ERROR PRESENTED
}
public void makeSelfCall() {
callDoit(this);
}

public String toString() {
return getClass().getName() + "[" + name + "]";
}
}



package x;

public class Base {
protected void doit() {
System.out.println("protected method " + getClass().getName() + ".doit() is called from class in " + getClass().getPackage());
}
}

Topic: If class Y extends class X, the two classes are in different packages... Previous Topic   Next Topic Topic: Eclipse and J2ME

Sponsored Links



Google
  Web Artima.com   

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