| ClassA | ClassB |
|---|---|
public class ClassA
{
public double var1 = 3.14;
public void method1()
{
System.out.println("Hi..");
}
}
|
public class ClassB
{
// Completely empty...
}
|
Notice that:
|
public class Test
{
public static void main(String[] args)
{
ClassB b = new ClassB();
System.out.println( b.var1 );
b.method1();
}
}
|
Because the instance variable var1 and the instance method method1 are not defined inside a ClassB object, the Java compiler will report these "identifier undefined" errors:
> javac Test.java Test.java:7: cannot find symbol symbol : variable var1 location: class ClassB System.out.println( b.var1 ); ^ Test.java:9: cannot find symbol symbol : method method1() location: class ClassB b.method1(); ^ 2 errors |
(The Java compiler can not find variable var1 and method method1() inside the object b)
How to do the experiment:
|
| ClassA | ClassB |
|---|---|
public class ClassA
{
public double var1 = 3.14;
public void method1()
{
System.out.println("Hi..");
}
}
|
public class ClassB extends ClassA
{
// Completely empty...
}
|
Notice that:
|
(And explain it later)
public class Test
{
public static void main(String[] args)
{
ClassB b = new ClassB();
System.out.println( b.var1 );
b.method1();
}
}
|
(Recall that ClassB is empty !!!)
The Java compiler will report no errors !!!
3.14 Hi, I'm method1 in ClassA |
Wait a minute... 3.14 ???
Isn't that the value of
the variable var1
defined
inside ClassA ???
And b.method1() prints the same message as the method1() inside ClassA ???
Hmmmm....
How to do the experiment:
|
|
|
|
|
Summary:
|
Note:
|
|
public class ClassA
{
public static double var1 = 3.14;
public static void method1()
{
System.out.println("Hi, I'm the STATIC method1 in ClassA");
}
}
public class ClassB extends ClassA
{
// Completely empty...
}
|
The output is:
777.0 |
So: ClassB.var1 and ClassA.var1 are different names for the same variable (alias !)