This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
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: 2341
posted
0
m is a private method of A. You can't access it in B.
Balaji VR
Ranch Hand
Joined: Mar 22, 2006
Posts: 76
posted
0
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
Greenhorn
Joined: May 01, 2006
Posts: 17
posted
0
class A{ private void m(){ System.out.println("A"); } } class B extends A{ private void m(){ System.out.println("B"); } public static void main(String [] args){ A x = new A(); B y = new B(); x.m(); y.m(); } }
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. Binesh
Sreeram Desigan
Greenhorn
Joined: Apr 07, 2006
Posts: 23
posted
0
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
Greenhorn
Joined: May 15, 2006
Posts: 17
posted
0
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: 44
posted
0
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.
mfg, Flom
Khaled Abdulraouf
Greenhorn
Joined: May 18, 2006
Posts: 2
posted
0
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
posted
0
calling the method m() with a parent type reference 'y' will cause a compilation error
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.