Hello everybody !!!
Given the code below:
package JavaLibrary1;
import java.io.*;
public class Print {
public Print(){ System.out.println("HELLO");};
public static void print(Object obj) {System.out.println(obj);}
public static void print() {System.out.println(); }
public static void printnb(Object obj) { System.out.print(obj); }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
package chapter8ex3;
import static JavaLibrary1.Print.*;
class Derived {
int x=9;
// void print(int x){} (1) if I compile with this method its OK
void print(){
print(x); //(2) gives complier error
//JavaLibrary1.Print.print(x); (3) if I’m explicit its OK
}
}
public class Chapter8Ex3 {
public static void main(
String[] args) {
Derived d=new Derived();
d.print();
print("HH"); // (4) it compiles
}
}
I have the following Q:
When I compile the code I get an error at line (2) with a message saying :
„print() in chapter8ex3.Derived cannot be applied to (int) print(x);
1 error”
Line (4) its OK
However if I’m explicit as in line (3) it compiles.
I thought is has something to do with the fact that methods print() and print(x) have the same name
and the latter is in the scope of the former
I looked up in JLS 7.0 and I found this under Shadowing 6.4.1:
* A declaration d of a method named n shadows the declarations of any other methods
named n that are in an enclosing scope at the point where d occurs throughout the
scope of d.
*/
But if this is true then line (1) should give an error but it doesn’t !!!
Thanks