aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "overriding" Watch "overriding" New topic


Binesh Thusantha

Joined: May 01, 2006
Posts: 17

when I compile this code through Java 5 version their come compilation error. pleas explain what is the reason for that.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
m is a private method of A. You can't access it in B.
Balaji VR
Ranch Hand

Joined: Mar 22, 2006
Posts: 76
Here we have got 2 cases -> Lets address one by one

Case (1) x.m();

This line absolutely ruled out. The code tries to access a private method outside its class. Strict NO!! NO!! to this.

Case (2) y.m();

Objects are created only during runtime. And Java compiler does n't know what Object the reference (Here "y") is referring to.
Hence, according to Java compiler, the code "y.m()" states that "y" is just the reference to the class "A"..hence the error (As per Case(1)'s rule)

Happy Learning!

Bala<br />SCJP 1.4 98%<br />SCBCD 1.3 -- 88%
Binesh Thusantha

Joined: May 01, 2006
Posts: 17
class A{
private void m(){
class B extends A{
private void m(){
public static void main(String [] args){
A x = new A();
B y = new B();

If i change B y = new A(); as B y = new B(); but the compiler complain the error. so what please explain what is the reason.
Sreeram Desigan

Joined: Apr 07, 2006
Posts: 23
The line B y = new A() will result in error because u can add a derived class object to a base class reference but not a base class reference to a derived class. Here A is a base class and B is a derived class.
tapan saha

Joined: May 15, 2006
Posts: 17
Hi Binesh ,

Compilation error is coming for x.m() [ as m() has private access in A]. After your change, problem at y.m() is gone. If you remove x.m() it will run fine.
Flom Xanther
Ranch Hand

Joined: May 26, 2006
Posts: 48
Hi Binesh,

remember, you can not call private methods/read private attributes from outside of the class, wich defines the private methods/attributes!

You should read
JLS 6.6 for the access modfiers of java.

Khaled Abdulraouf

Joined: May 18, 2006
Posts: 2
Please confirm,calling the method m() with a parent type reference 'y' will not cause a compilation error.
as this was the output:
The method m() from the type A is not visible

<b>Success is going from failure to failure without a loss of enthusiasm.</b>
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
calling the method m() with a parent type reference 'y' will cause a compilation error
It is sorta covered in the JavaRanch Style Guide.
subject: overriding