• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Packages

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Source : Marcus Green Mock Exam Questions

What happens when you attempt to compile and run these two files in the same directory?

//File P1.java
package MyPackage;
class P1{
void afancymethod(){
System.out.println("What a fancy method");
}
}
//File P2.java
public class P2 extends P1{
afancymethod();
}
1) Both compile and P2 outputs "What a fancy method" when run
2) Neither will compile
3) Both compile but P2 has an error at run time
4) P1 compiles cleanly but P2 has an error at compile time

Answer :
4) P1 compiles cleanly but P2 has an error at compile time

Even though P2 is in the same directory as P1, because P1 was declared with the package statement it is not visible from P2
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So, what's your question? The directory structure must match the package structure. If it doesn't, you'll get errors.
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
first off, the class definition for P2 is wrong..where is the declaration for the method containing the call afancymethod? it's missing. P2 will not even compile because it's not Java syntax ;-)

second, the answer is not too clear, the reason it will not compile is because afancymethod is package private and hence not visible from P2 since P2 is in a different package.

Also, the compile directory has to be "MyPackage", if not you'll get errors.

Also, the classpath to the compiler has to be specified as one level below "MyPackage" otherwise you'll get more errors.

Another thing...the import statement is missing for P2
[ June 27, 2008: Message edited by: Kevin Smither ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic