开发者

Naming a class after its direct ancestor

It is possible in Java to do sth like:

Class packageName1.foo extends packageName2.foo { ...  ?

Where foo == foo.

This would mean, that you can simply change the name of imported package, to get sth done differently (without cha开发者_如何学运维nging type of each reference to interface name ).


You can do this:

package some.package.name;

class Foo extends some.other.package.Foo { ... }

I would not recommend this, however, as it will probably lead to less-clear code, and encourage programming errors. A better way to do this sort of thing is to abstract the common functionality into an interface, and then write different implementing classes:

class FooImpl implements Foo { ... }

class OtherFooImpl implements Foo { ...}

then you'd use it like this, in some other bit of code somewhere:

...
Foo myFoo = new FooImpl();
// use myFoo
...

and if you want to change the implementing class, then you simply change how it's instantiated:

...
Foo myFoo = new OtherFooImpl();
// use myFoo
...

This is a much more common practice in Java than what you asked about.


The package is part of the fully qualified class name. Using the "short names" is really just syntactic sugar.

That also means that "changing the name of the imported package" is the same thing as changing the type of each reference, it just happens at a different place in the source file - certainly more convenient if you think about the number of places you need to change, but that's something a good IDE can do for you automatically. On the other hand, having different classes with the same short name can lead to confusion.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜