• 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Junilu Lacar
  • Liutauras Vilda
Sheriffs:
  • Paul Clapham
  • Jeanne Boyarsky
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
Bartenders:
  • Jesse Duncan
  • Frits Walraven
  • Mikalai Zaikin

Mock Exam Question

 
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
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 given is 4 .
But Why ?
 
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
P1 is in package MyPackage, but P2 is not specified, so it is in the default package. Still everything would be ok if class P1 was public, but it isn't. It has not access modifier so it only has package accessibility. Different pacakges, so it can't be seen when you try to compile P2. You end up getting an error message that says class P1 can't be found.
Bill
 
drifter
Posts: 1364
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
P2 actually has several problems:
Method afancymethod in P2 has no return type.
Method afancymethod in P2 has no body.
P2 can't see P1 whether P1 is public class or default class as P2 is in package MyPackage (P1 in default package) and they are in the same directory and P2 has no import statement for MyPackage.
 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Carol,
I think that the line
afancymethod();
in P2 is a call to the afancymethod method in P1 and not a method declaration.So there isn't a missing return type or a method body in this case.The only reason P2 does not compile because it is in default package and is trying to access a method in parent class which is not visible in this package.
Have Fun,:-)
Gazala.
reply
    Bookmark Topic Watch Topic
  • New Topic