【问题标题】:Implement Serializable to a class implementing an Interface将 Serializable 实现为实现接口的类
【发布时间】:2015-01-27 13:53:43
【问题描述】:

我有一个名为 Person 的超类,它被另外两个类 EmployeeClient 继承 我正在使用一个接口,以便我可以在两个子类上使用泛型,因此 Person 类实现了这个接口,Searchable。 Person 类是否可以同时实现接口和 Serializable 以便我可以保存?

package compuwiz;
public abstract class Person implements Searchable //implements Serializable ??
{
public Person()
{
    pName = "";
    pSurname = "";
    pIdCard = "";
}
public Person(String nm, String sn, String id)
{
    pName = nm;
    pSurname = sn;
    pIdCard = id;
}
String pName;
String pSurname;
String pIdCard;
public String GetName()
{
    return pName;
}
public String GetSurname()
{
    return pSurname;
}

@Override
public String GetID()
{
    return pIdCard;
}
//Set Methods
public void SetName(String nm) 
{
  pName=nm;  
}
public void SetSurname(String sn) 
{
  pSurname=sn;  
} 
public void SetID(String id) 
{
  pIdCard=id;  
}

@Override
public String ToString()
{
    return this.GetName()+ " " +this.GetSurname()+ "ID card number:" +this.GetID();
}

【问题讨论】:

    标签: java interface implementation serializable implements


    【解决方案1】:

    是的。这就是接口的目的。一个类可以同时实现多个接口:

    public abstract class Person implements Searchable, Serializable {
        //current code of your class...
    }
    

    除此之外,我建议使用正确的方法命名。也就是说,使用camelCase 标准,第一个字母小写,然后你使用大写作为名称中包含的下一个单词。示例:

    //this will throw a compiler error unless you define a ToString method in a top interface
    @Override
    public String ToString() {
    }
    

    @Override
    public String toString() {
    }
    

    【讨论】:

    • 非常感谢!我很感激。
    【解决方案2】:
    public abstract class Person implements Serializable, Searchable {}
    

    Java 支持多接口继承

    【讨论】:

    • 非常感谢!没想到
    猜你喜欢
    • 1970-01-01
    • 2012-08-03
    • 2013-12-31
    • 2011-10-26
    • 2011-05-28
    • 2011-11-10
    • 1970-01-01
    • 2012-07-20
    • 2011-09-26
    相关资源
    最近更新 更多