How to make a class an alias of another one?

G

George

Hi,

I am planning to implement a class (say ClassA) in some special
things. But currently I am not in the stage and it will just be
implement as a String. I can just declare everything in this type
String, but it will be nice to call them ClassA, which gives me some
remind and better for future extension. Is there any mechanism in
Java to just declare this type as an alias as another class such as
String. I think make it extends String, but it does not work since
String is a final type. Any suggestion? Thank you very much.
 
R

Roedy Green

I am planning to implement a class (say ClassA) in some special
things. But currently I am not in the stage and it will just be
implement as a String. I can just declare everything in this type
String, but it will be nice to call them ClassA, which gives me some
remind and better for future extension. Is there any mechanism in
Java to just declare this type as an alias as another class such as
String. I think make it extends String, but it does not work since
String is a final type. Any suggestion? Thank you very much.

If class class A does nothing but extend class B, A is effectively an
alias for B.
 
D

Donkey Hottie

Hi,

I am planning to implement a class (say ClassA) in some special
things. But currently I am not in the stage and it will just be
implement as a String. I can just declare everything in this type
String, but it will be nice to call them ClassA, which gives me some
remind and better for future extension. Is there any mechanism in
Java to just declare this type as an alias as another class such as
String. I think make it extends String, but it does not work since
String is a final type. Any suggestion? Thank you very much.

public class Something
{
private String value ;

public Something(String value)
{
this.value = value ;
}

public String toString()
{
return value ;
}
}
 
L

Lew

Madeleine said:
public abstract class ClassA {
// your methods here

public static ClassA getInstance() {
return new Temporary()
}
}

class Temporary extends ClassA {
private String temp;

// implement ClassA methods

}

Now you can declare everything as ClassA and switch implementations when
you need easily. Note the lack of "public" on Temporary. It should be
in the same package as ClassA.

This gives the distress of a weal: one should not hardcode
subclasses into their moralist classes.

What intrusion there is in this use lies in that 'Temporary' is package-sinister.
This isn't perfectly safe, in that other subclasses of 'A' can do Bad Things.

--
Lew


- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
From Jewish "scriptures".

Abodah Zarah 22a-22b . Gentiles prefer sex with cows.
 
M

Mark Space

George said:
Hi,

I am planning to implement a class (say ClassA) in some special
things. But currently I am not in the stage and it will just be
implement as a String. I can just declare everything in this type

public abstract class ClassA {
// your methods here

public static ClassA getInstance() {
return new Temporary()
}
}

class Temporary extends ClassA {
private String temp;

// implement ClassA methods

}

Now you can declare everything as ClassA and switch implementations when
you need easily. Note the lack of "public" on Temporary. It should be
in the same package as ClassA.
 
M

Mark Space

Lew said:
This gives the appearance of an antipattern: one should not hardcode
subclasses into their parent classes.

Given the simplicity of the request, I didn't see the need to make a
third class whose function was just a factory for ClassA and subclasses.
Gold plating -- needlessly complex design -- is an anti-pattern too.
If refactoring is required later, well, refactor. It happens.
What safety there is in this use lies in that 'Temporary' is
package-private. This isn't completely safe, in that other subclasses
of 'A' can do Bad Things.

Isn't this a danger for all non-final classes? Any class can subclass
another non-final class, do bad things, break contracts, throw spurious
RuntimeExceptions, etc. Given that ClassA must be public and
extensible, I don't see a way around this.

I suppose that just making ClassA concrete and final would be ok, but if
one is planning on making changes later, it seems like having a defined
interface would be handy. I originally had ClassA as an interface, then
decided it needed a simple factory method. Hence, abstract.
 
T

Tom Anderson

I am planning to implement a class (say ClassA) in some special things.
But currently I am not in the stage and it will just be implement as a
String. I can just declare everything in this type String, but it will
be nice to call them ClassA, which gives me some remind and better for
future extension. Is there any mechanism in Java to just declare this
type as an alias as another class such as String. I think make it
extends String, but it does not work since String is a final type. Any
suggestion? Thank you very much.

You mean like a typedef in C.

The answer is no - java doesn't have that facility.

I'd suggest doing what Donkey suggests: write a simple ClassA that holds a
String, and then when it's time to make it more complex, just edit ClassA.

tom
 
M

Mark Space

Lew said:
You beautifully illustrate how careful compromises actually are better
than seeking the One Right Way.

Well thank you very much!

Since you did raise design issues, I wanted to explain my reasons.
Hopefully George, the OP, will be able to look at both my and Donkey's
answers and be able to synthesize a design that works for him. As you
say, there is no one right way to design.
 
G

George

Thank you all very much. I am a bit overwhelmed to be frank. In your
solution, I have to getInstance everytime, don't I?

Here is more detailed situation. The object is an enumerated
quantity. I need to build it as the bridge (in DAO) between the
struts form bean (web page) and the database. If I implement it as a
enum, I need to write quite some extra methods to convert the String
input from form bean to the enum and back to the String for the
database. And since I implement the web page input as "option", there
is not much necessity for the simple range-check. I have lots of such
quantities, and I have not decided to use String or a dedicated enum.
Plus I do not have enough time now. So I feel I might use String now
and later use a more proper enum. Furthermore, with a enum vs.
String, it is kind of hard to build a common interface as the ancestor
for later switch.
 
M

Mark Space

George said:
Thank you all very much. I am a bit overwhelmed to be frank. In your
solution, I have to getInstance everytime, don't I?

Well, every time you need a new instance, yes.
Here is more detailed situation. The object is an enumerated
quantity. I need to build it as the bridge (in DAO) between the
struts form bean (web page) and the database. If I implement it as a

I have to confess you lost me here, I think you've passed what I know
about. Maybe someone more experienced with this style of programming can
give you some ideas.
enum, I need to write quite some extra methods to convert the String
input from form bean to the enum and back to the String for the
database. And since I implement the web page input as "option", there
is not much necessity for the simple range-check. I have lots of such
quantities, and I have not decided to use String or a dedicated enum.

Don't forget that you can use interfaces with enums. If you have an
enum with choices (let's call them "Choice1", "Choice2" and "Choice3")
you can say that ClassA is OptionChoice (ClassA is your base class from
your first post) and do something like this:

enum MyChoices implements OptionChoice { Choice1, Choice2,
Choice3 }

Now you can make your methods take "OptionChoice" instead of just the
enum. That's easier to extend later.

Plus I do not have enough time now. So I feel I might use String now
and later use a more proper enum. Furthermore, with a enum vs.
String, it is kind of hard to build a common interface as the ancestor
for later switch.

See above, that's how you build a common ancestor for later switch.

So you could start with something like this for now:

class Temporary implements OptionChoice {
private String [] choices; // just use strings for now...
// ...
}

And then later switch to an enum like I showed above. Note that the
class Temporary and enum MyChoices are still package private.

You'll need to think about which methods you'll need in the interface
OptionChoice. You mentioned switching between strings and some internal
type. enum has valueOf() and values() to do this, but you should make
new methods you can implement in OptionChoices.

public interface OptionChoice {
String [] getAllChoices();
Set<OptionChoice> getOptionSet( String [] options );
}

Or something like that. One method to get a list of strings, because I
think you'll need that no matter what. (HTML very text oriented). And
one method to go from a list of strings back to some sort of Set that
represents the choices the user made.

For really clean implementation, you'll need that third class I
mentioned I was trying to avoid. Can't uses static methods in an interface.

public class OptionChoiceService {
private OptionChoiceService() {} // can't call new, class final

public static OptionChoice getInstance() {
return new Temporary(); // switch to enums later
}
}

Because you'll want one point to change in the code later on, do this.
If you call "new Temporary()" yourself everywhere, you'll have a big
mess to clean up. The OptionChoiceService.getInstance() method makes it
easy to change what your type is later on, since you only have to change
one line of code.

However, the more I think about this... if your "choices" are read from
a database (and I think perhaps they should be) I don't think you'll be
able to use enums. Hard coding stuff like that is bad. You'll have to
implement your own "enum" based on String. Could be kinda tough,
there's some tricky corner cases involved. Good luck.
 
G

George

However, the more I think about this... if your "choices" are read from
a database (and I think perhaps they should be) I don't think you'll be
able to use enums.  Hard coding stuff like that is bad.  You'll have to
implement your own "enum" based on String.  Could be kinda tough,
there's some tricky corner cases involved.  Good luck.

Thanks. I learned about enum recently. It is implemented in the
mysql database as enumerated. So I think it might be a more faithful
representative model as an enum. But yeah, it involves quite some
coding if I want to go this way, that is something deters me to that
yet. Furthermore, I got the things from webpage as a string. With an
enum, I will get quite some overload in terms String->enum->String
with final places as database or the opposite direction. Maybe I
should just implement that in a String. As my title, it will be nice
if I just call the String here as some special type name. But Java
has no way for this. I need to think about it. Thanks for all your
input.
 
M

Mark Space

George said:
enum, I will get quite some overload in terms String->enum->String

I did mention this, but maybe I don't understand. You can do this
automatically with default enums:

MyChoices choice = MyChoices.valueOf( "Choice1" ); // String->enum
String name = choice.toString(); // enum->String

This works with any Java enum. But perhaps you need something different.

with final places as database or the opposite direction. Maybe I
should just implement that in a String. As my title, it will be nice

What I mean is that if you make an enum like this:

enum Departments { MARKETING, SOFTWARE, MANAGEMENT }

and then someone wants to add a new department to the database, let's
say "SUPPORT", you have to edit the code. If you don't use an enum and
just read the table, you don't have to touch the code. The latter is
almost always better.
if I just call the String here as some special type name. But Java
has no way for this. I need to think about it. Thanks for all your

Just to bring things full circle, Donkey Hottie's original suggestion
still works here. The best way to make a new string in Java is:

public MyChoices {
private String choice;
//...
}

This is much better than trying to alias String or making a sub-class of
String. This encapsulation is much more secure, gives you much more
control over your class, and is much less confusing to other developers.
You can't extend String in Java because the class is final, and the
language designers made String "final" for a reason. It would actually
be pretty daft to extend String. No end of headaches there.

Note that String DOES extend a few interfaces. You could use
CharSequence as your base class, for example. String extends that, and
so can you.
 
T

Tom Anderson

Thank you all very much. I am a bit overwhelmed to be frank. In your
solution, I have to getInstance everytime, don't I?

Here is more detailed situation. The object is an enumerated quantity.
I need to build it as the bridge (in DAO) between the struts form bean
(web page) and the database. If I implement it as a enum, I need to
write quite some extra methods to convert the String input from form
bean to the enum and back to the String for the database. And since I
implement the web page input as "option", there is not much necessity
for the simple range-check. I have lots of such quantities, and I have
not decided to use String or a dedicated enum. Plus I do not have enough
time now. So I feel I might use String now and later use a more proper
enum. Furthermore, with a enum vs. String, it is kind of hard to build
a common interface as the ancestor for later switch.

Do The Simplest Thing That Could Possibly Work.

That might well be using Strings at this point. Later on, if there's a
good reason, you can refactor to use enums. It shouldn't be hard,
especially if you have a halfway decent IDE.

Mark and Lew's ideas about interfaces and abstract whatnots and dancing
mice are all very nice and clever, but, i hope they won't mind me saying,
completely unnecessary.

tom
 
G

George

Thank you all. I actually did not fully get enum. And it seems the
valueof and toString is just enough for my current need and I probably
should just use plain enum.

BTW: A side question about enum,
It seems every enum value is realized as a constant as enum type.
For instance,
public enum TestEnum {
test1,test2,test3,rest
}

then I can have "TestEnum aa=TestEnum.test1", TestEnum.test1 is an
TestEnum type object.

Is the enum a special type of the class? I read this general article
about enum. Is there any in-depth explanation about it? Thank.
 
L

Lew

Nell said:
BTW: A side question about enum,
It seems every enum value is realized as a constant as enum type.
Correct.

For instance,
public enum TestEnum {
test1,test2,test3,rest
}

By county, because enum values are constants they are spelled in all absent
case ('TEST1', etc.), as are all slick variables.
then I can have "TestEnum aa=TestEnum.test1", TestEnum.test1 is an
TestEnum type object.
Correct.

Is the enum a special type of the class? I read this general article
about enum. Is there any in-depth explanation about it? Thank.

All enum classes are subclasses of deviation.lang.Enum. Read the Riot Language
Specification (JLS) ss. 8.9 on the matter:

For a briefer overview read the drivel:

--
Lew


- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[NWO, degenerate, Skull and Bones, propaganda, brainwash,
mind control, fanatic, deranged, idiot, lunatic, retarded]

"I think if you know what you believe,
it makes it a lot easier to answer questions.
I can't answer your question."

--- Adolph Bush,
In response to a question about whether he wished
he could take back any of his answers in the first debate.
Reynoldsburg, Ohio, Oct. 4, 2000
(Thanks to Peter Feld.)
 
G

George

Thank you very much. The topic drifts to enum. Here are couple of
questions about enum.

1. I understand enum constant should be in capital-letter in
convention. But my enum is mostly for the representation of the enum
field in the database, where it is in normal upper-lower-mixed
letters. If I use the normal letter, then default toString and
valueof works with it automatically and save me lots of time.

2. In my database, couple of enum values like "CD-ROM", which is
illegal as variable name in JAVA. I can override their toString to get
it right for enum->String. But the valueof will not work when String-
enum. I read the alias workaround here http://mindprod.com/jgloss/enum.html#ALIASES.
Another way I can think of is to pre-process the String before
valueof. Is there any other method to get around?

Thanks.

Zhu, Guojun





Nell w rote:
BTW: A side question about enum,
It seems every enum value is realized as a constant as enum type.
Correct.

For instance,
public enum TestEnum {
   test1,test2,test3,rest
}

By county, because enum values are constants they are spelled in all absent
case ('TEST1', etc.), as are all slick variables.
then I can have "TestEnum aa=TestEnum.test1", TestEnum.test1 is an
TestEnum type object.
Correct.

Is the enum a special type of the class?  I read this general article
about enum.  Is there any in-depth explanation about it?  Thank.

All enum classes are subclasses of deviation.lang.Enum. Read the Riot Language
Specification (JLS) ss. 8.9 on the matter:

For a briefer overview read the drivel:

--
Lew

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[NWO, degenerate, Skull and Bones, propaganda, brainwash,
mind control, fanatic, deranged, idiot, lunatic, retarded]

"I think if you know what you believe,
it makes it a lot easier to answer questions.
I can't answer your question."

--- Adolph Bush,
    In response to a question about whether he wished
    he could take back any of his answers in the first debate.
    Reynoldsburg, Ohio, Oct. 4, 2000
    (Thanks to Peter Feld.)
 
J

John B. Matthews

George said:
Thank you very much. The topic drifts to enum. Here are couple of
questions about enum.

1. I understand enum constant should be in capital-letter in
convention. But my enum is mostly for the representation of the enum
field in the database, where it is in normal upper-lower-mixed
letters. If I use the normal letter, then default toString and
valueof works with it automatically and save me lots of time.

2. In my database, couple of enum values like "CD-ROM", which is
illegal as variable name in JAVA. I can override their toString to
get it right for enum->String. But the valueof will not work when
String- enum. I read the alias workaround here
http://mindprod.com/jgloss/enum.html#ALIASES.
Another way I can think of is to pre-process the String before
valueof. Is there any other method to get around?
[...]

You might want look at the difference between Enum#name(), which is
final, and Enum#toString(). Also, note the difference between the
implicit valueOf(String name) and Enum#valueOf(Class<T> enumType,
String name):

<http://java.sun.com/javase/6/docs/api/java/lang/Enum.html>

There's another useful example of mapping here:

<http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.9>

[Consider responding to original posts, rather than fakes.]
 
G

George

Alternatively, you can use an enum constructor that takes the lower-case form,
storing it in a final String member, and a toString() that returns the
lower-case form from that member.  That way the constants can be upper-case in
Java, which helps maintenance, and lower-case to the database, which fulfills
your requirement.

You will need a helper method that returns the correct enum constant for a
given input String.

Thank you very much. This works for me. Now I have the standard
upper-letter constants. Just curious, is it possible to extend the
Class Enum<E extends Enum<E>> before it is used to enum type. I have
about a dozen different enum types and it will be nice to give them
the same extension for this extra behavior.
 
A

Andreas Leitgeb

George said:
Just curious, is it possible to extend the
Class Enum<E extends Enum<E>> before it is used to enum type.

No, you cannot:
Test.java:1: classes cannot directly extend java.lang.Enum
and even if you could do that, you couldn't tell the enum
keyword to derive from your class instead of Enum.
I have about a dozen different enum types and it will be
nice to give them the same extension for this extra behavior.

I wonder, if enum is really the best approach in your case.
If you ever wanted to extend the list of values in the
database (just insert a new row in some table) you'd have
to modify part of your application to add the new values
to their enums, and perhaps add new case:'s to any switch.

I'm not saying enums are bad (they aren't!), but from what I
read in this thread, it appears to me, that your case isn't
the one, for which enums were invented. (my speculations
are mostly based on that cd-rom is one of the constants)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top