当前位置: 技术问答>java相关
如何用JAVA定义枚举类型的类
来源: 互联网 发布时间:2015-09-25
本文导语: 我想定义一个类,只有一个类型。 此类型可能是类型A,也可能是类型B。 For example: Type address= A | B 请问如何定义? 下面是我对固定类型定义的类 class ADDRESS{ HashMap m; public ADDRESS(){m= new HashMap;} } 也就是说, 如...
我想定义一个类,只有一个类型。
此类型可能是类型A,也可能是类型B。
For example:
Type address= A | B
请问如何定义?
下面是我对固定类型定义的类
class ADDRESS{
HashMap m;
public ADDRESS(){m= new HashMap;}
}
也就是说, 如果m可能是其它类型,比如说HashTable,
如何定义?
此类型可能是类型A,也可能是类型B。
For example:
Type address= A | B
请问如何定义?
下面是我对固定类型定义的类
class ADDRESS{
HashMap m;
public ADDRESS(){m= new HashMap;}
}
也就是说, 如果m可能是其它类型,比如说HashTable,
如何定义?
|
这个AddressEnum类是不是你想要的?AddressEnumTest是测试类。在j2sdk1.4.0 ,WINDOWS2000 ,JCreator Pro 2.5 调试通过。
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public class AddressEnum{
private HashMap hm = new HashMap();
private Hashtable ht = new Hashtable();
public AddressEnum(){}
public setHashMap(Map m){
this.hm.putAll(m);
}
public setHashtable(Map t){
this.ht.putAll(t);
}
public HashMap getHashMap(){
return hm;
}
public Hashtable getHashtable(){
return ht;
}
}
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public class AddressEnumTest{
public static void main(String args[]){
HashMap hm = new HashMap();
Hashtable ht = new Hashtable();
AddressEnum ae = new AddressEnum();
hm.put("001","HashMap001");
ht.put("101","Hashtable101");
ae.setHashMap(hm);
ae.setHashtable(ht);
System.out.println(ae.getHashMap());
System.out.println(ae.getHashtable());
}
}
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public class AddressEnum{
private HashMap hm = new HashMap();
private Hashtable ht = new Hashtable();
public AddressEnum(){}
public setHashMap(Map m){
this.hm.putAll(m);
}
public setHashtable(Map t){
this.ht.putAll(t);
}
public HashMap getHashMap(){
return hm;
}
public Hashtable getHashtable(){
return ht;
}
}
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public class AddressEnumTest{
public static void main(String args[]){
HashMap hm = new HashMap();
Hashtable ht = new Hashtable();
AddressEnum ae = new AddressEnum();
hm.put("001","HashMap001");
ht.put("101","Hashtable101");
ae.setHashMap(hm);
ae.setHashtable(ht);
System.out.println(ae.getHashMap());
System.out.println(ae.getHashtable());
}
}
|
错了,下面才对。
public class AddressEnum{
public static final AddressEnum AddressA = new AddressEnum("A");
public static final AddressEnum AddressB = new AddressEnum("B");
private String address;
private AddressEnum(String address){
this.address = address;
}
public String toString(){
return address;
}
}
public class AddressEnum{
public static final AddressEnum AddressA = new AddressEnum("A");
public static final AddressEnum AddressB = new AddressEnum("B");
private String address;
private AddressEnum(String address){
this.address = address;
}
public String toString(){
return address;
}
}
|
java 没有枚举类型,你只能把它定义为静态常量
|
用抽象类不行吗?