Yes, Java will let you subclass a non-final
concrete class just for the purposes of aliasing the original class.
public class Foo { /* implementation */ }
public class Bar extends Foo {}
That would be the minimal implementation, assuming that there is only a default constructor in Foo
. If there are constructors that take arguments in Foo
, then you must provide a constructor in Bar
for every constructor you plan to call to create your Bar
instances, e.g.:
public class Foo {
public Foo(String baz) { /* constructor implementation */ }
}
public class Bar extends Foo {
public Bar(String baz) { super(baz); }
}
All non-private
methods in Foo
will be inherited by Bar
.
The only place it might not work is if you intend to use Bar
in place of Foo
as a generic type parameter.
For example, if you replace a List<Foo>
with a List<Bar>
, then your List
can no longer hold any Foo
instances, or instances of any other class that might extend Foo
.
Additionally, because Java's generics are invariant, a List<Bar>
is not a subtype of List<Foo>
, even if a Bar
is a Foo
. See Is List a subclass of List? Why aren't Java's generics implicitly polymorphic? for details on why that is the case. Also, you may be able to get around it if you use List<? extends Foo>
so that you can use a List<Foo>
or a List<Bar>
, but then you won't be able to add
anything but null
.
You state that you won't be using it in generics, but it's worth keeping in mind if your requirements are expanded.
In conclusion, yes, the Java compiler will let you do it, but with a limited upside -- using Bar
instead of Foo
as an alias -- and a potential downside, I see no reason to use this aliasing process.