当前位置: 代码迷 >> Java相关 >> 接口中方法的实现问题?
  详细解决方案

接口中方法的实现问题?

热度:119   发布时间:2007-02-10 19:24:42.0
接口中方法的实现问题?

import java.util.Arrays;

public class MuilInterfaceTest
{
public static void main(String[] args)
{
Student[] staff = new Student[3];
staff[0] = new Student("Tom", "20031020");
staff[1] = new Student("Jack", "20031022");
staff[2] = new Student("Rose", "20021023");

Arrays.sort(staff); ××××需要实现接口 Comparable;

for(int i = 0; i < staff.length; i++)
{
System.out.println((Student)staff[i]);
}
}
}

interface Person
{
String getName();
String getSex();
String getBirthday();
String getAddress();
void setAddress(String strAddress);
}

class Student implements Person, Comparable
{
private String strName = "";//学生姓名
private String strNumber = "";//学号
private String strSex = "";//性别
private String strBirthday = "";//出生年月
private String strSpeciality = "";//专业
private String strAddress = "";//地址

public Student(String name, String number)
{
strName = name;
strNumber = number;
}

public int compareTo(Object otherObject)
{
Student other = (Student)otherObject;
int otherNumber = Integer.parseInt(other.strNumber);
int thisNumber = Integer.parseInt(this.strNumber);


if(thisNumber > otherNumber)
return 1;
else if (thisNumber == otherNumber)
return 0;
else
return -1;
}

public String getName()
{ ....................
. .................
}
public String toString()
{
String information = "学生姓名=" + strName + ", 学号=" + strNumber;
if( !strSex.equals("") )
information += ", 性别=" + strSex;
if( !strBirthday.equals(""))
information += ", 出生年月=" + strBirthday;
if( !strSpeciality.equals("") )
information += ", 专业=" + strSpeciality;
if( !strAddress.equals("") )
information += ", 籍贯=" + strAddress;
return information;
}
}


compareTo 个方法是怎么实现的?并没有变量调用它呀?
也没有声明为abstract类呀??
不懂。
谢谢。

搜索更多相关的解决方案: 接口  

----------------解决方案--------------------------------------------------------
Arrays.sort(Object[] a);这个方法要求数组中的所有元素都必须实现 Comparable 接口
实现Comparable接口就要给出compareTo方法的实现
具体说明请查api
----------------解决方案--------------------------------------------------------
那么可不可以这么理解:
一个类实现了一个接口,就是说类要实现接口的所有方法。要实现接口里的所有方法,则这个类的所有对象会对这个接口里的所有方法进行调用。所用的参数就是对象变量初始化的值?

谢谢。
----------------解决方案--------------------------------------------------------

实现接口就是实现他所提供的所有方法
调不调用那就是你的事了


----------------解决方案--------------------------------------------------------
接口只相当于一个规范。
----------------解决方案--------------------------------------------------------

什么叫“做实现它所提供的方法”呢?
是不是就是在实现接口的类中把接口里面定义的方法按具体需要写出来就行了?


谢谢。


----------------解决方案--------------------------------------------------------
恩 你说的没错
----------------解决方案--------------------------------------------------------
  相关解决方案