覆盖和超载

时间:2010-12-29 22:11:40

标签: java overloading override

public class Module
{
    // required instance variables
    private String codeModule, titleModule;
    private int pointsModule;

    //three-argument constructor receiving a code, a title string, and a        
    //number of points, 
    //which sets the code, title and points data of the created object to    
    //the received values.
    public Module(String aCode, String aTitle, int aPoints)
    {
       codeModule = aCode;
       titleModule = aTitle;
       pointsModule = aPoints;
    }

    //set the instance data value codeModule to received argument newCode.
    public void setaCode(String newCode)      
    {
       codeModule = newCode;
    }

    //set the instance data value titleModule to received argument 
    //newTitle.                 
    public void setaTitle(String newTitle)      
    {
       titleModule = newTitle;
    }

    //set the instance data value pointsModule to received argument        
    //newPoints.
    public void setaPoints(int newPoints)      
    {
       pointsModule = newPoints;
    }

    //return the instance data values of codeModule.
    public String getaCode()
    {
       return codeModule;
    }

    //return the instance data values of titleModule.
    public String getaTitle()
    {
       return titleModule;
    }

    //return the instance data values of pointsModule.
    public int getaPoints()
    {
       return pointsModule;
    }

    //returns a string containing the full details of the module, 
    //giving the module code, title and number of points in parentheses
    public String toString()
    {
       return "Module code " + codeModule + ", Module Title " + titleModule + ", Module 
       Points (" + pointsModule + ")";
    }

    //returns true if the module referenced by o has the same instance       
    //variable values 
    //as the object on which this method is invoked; otherwise the method    

    public boolean equals(Object o)
    {
       Module m = (Module)o;
       return codeModule.equals(m.codeModule) && titleModule.equals(m.titleModule) && 
       pointsModule == m.pointsModule;
    }

    //returns true if the code string begins with a capital letter and has      
    //four characters; 
    //otherwise the method returns false.
    public Boolean isCode()
    {
       if (codeModule.length()== 4 && (codeModule.charAt(0) >=  'A'   
       &&(codeModule.charAt(2) <= 'Z')))  
       {
          return true;
       }
       else
       {
          return false;
       }
    }     
}

我被要求识别任何重载或覆盖任何其他方法的方法,据我所知,当一个类有多个具有相同名称但具有不同签名(即类型,数字或类型)的方法时会发生重载它们的形式参数的顺序必须不同)如果子类中方法的签名与继承方法的签名完全匹配并且它们具有,则子类中的方法定义将覆盖超类或其祖先类中的继承方法。相同的退货类型。 超类中的私有方法不会在子类中重写,因为它们不会被继承。

据我了解,我没有任何方法具有相同的名称,不能超载,我没有扩展另一个类,所以我不能覆盖!这是正确的还是我错过了什么。

由于 BB

(我也被要求从以前的问题格式正确,我希望这是正确的)

2 个答案:

答案 0 :(得分:6)

您的理解是正确的,但请记住,所有对象都隐式扩展java.lang.Object,因此您需要检查是否覆盖了该类中的任何方法。

答案 1 :(得分:1)

您的定义是正确的,toString()会覆盖Object

中的方法