views:

67

answers:

4
package a;
class hello{
}


package b;
import a.*;
class hello extends hello{
}

please tell me what is the result??

A: 

Wondering why you did not try compiling this yourself!

Compiler will report a "cyclic inheritance" error. class hello in package b should declared like this:

class hello extends a.hello { }

class hello in package a should be declared public to make it visible outside the package.

Vijay Mathew
+1  A: 

It will give you a compile time error. Because a.hello will never be imported, shadowed and class hello extends hello means that your class extends itself.

A type-import-on-demand declaration never causes any other declaration to be shadowed.

The example:

import java.util.*;

causes the simple names of all public types declared in the package java.util to be available within the class and interface declarations of the compilation unit. Thus, the simple name Vector refers to the type Vector in the package java.util in all places in the compilation unit where that type declaration is not shadowed (§6.3.1) or obscured (§6.3.2). The declaration might be shadowed by a single-type-import declaration of a type whose simple name is Vector; by a type named Vector and declared in the package to which the compilation unit belongs; or any nested classes or interfaces. The declaration might be obscured by a declaration of a field, parameter, or local variable named Vector (It would be unusual for any of these conditions to occur.)


Even if you use a single type import :

If another top level type with the same simple name is otherwise declared in the current compilation unit except by a type-import-on-demand declaration (§7.5.2) or a static-import-on-demand declaration (§7.5.4), then a compile-time error occurs.

So the sample program:

import java.util.Vector;
class Vector { Object[] vec; }

causes a compile-time error because of the duplicate declaration of Vector, as does:

import java.util.Vector;
import myVector.Vector;

The only way is to use the fully qualified name of a.hello in your b.hello class.


Resources :

Colin Hebert
A: 

We could regard package as first name, class as last name. Although we share last name with father, we are not same people. By such thought, inheritance is OK. Of course, "cyclic inheritance" should be avoided as Vijay mentioned.

卢声远 Shengyuan Lu
A: 

This is what the compiler would say:

b/Hello.java:3: b.Hello is already defined in this compilation unit
import a.Hello;
^

It can be solved however, by fully qualifying the class-name:

package b;
public class Hello extends a.Hello {
}

Side note: Java is very allowing when it comes to name overloading. This program for instance, compiles just fine.

package b;

public class Hello extends a.Hello {
    int Hello = 7;

    // Constructor
    public Hello() {
        Hello Hello;
    }

    // Method
    public Hello Hello() {
        Hello Hello = new Hello();
        return Hello;
    }
}
aioobe