Defining Instance Methods





The form of an instance method definition is


def <name>(self, <other args>):




A method definition has no explicit return type.  If a method does not return from a return statement, it automatically returns the value None.  Otherwise, the method returns the type of value returned by a return statement, or the value None if there is no such value.


The argument self is required for an instance method.  When the method is called, the called does not explicitly pass an argument in selfŐs position.  Instead, the PVM assigns to self the receiver object.


When a method is called, its arguments must match in number the corresponding parameters in the definition.  As usual, type checking is deferred to the point at which a value is needed for a type-specific operation.




class Student:


    // Variables and constructor


    def getName(self): return


    def getGrade(self, i):

        return self.grades[i – 1]


    def setGrade(self, i, newGrade):

        self.grades[i - 1] = newGrade



The form of an instance method definition is


<visibility modifier> <return type> <name>(<args>){




All methods must specify a return type.  If there is no value returned, this type must be void.  The value returned by any return statement must be type compatible with the methodŐs return type.  A non-void method must have at least one reachable return statement.



Each parameter in the method header, if there are any, must include the parameterŐs type.  The syntax of these is similar to that of variable declarations.




When a method is called, its arguments must match in number and type with the corresponding parameters in the methodŐs definition.  All type checking is done at compile time.






public class Student{


    // Variables and constructors


    public String getName(){




    public int getGrade(int i){

        return this.grades[i – 1];



    public void setGrade(int i, int newGrade){

        this.grades[i - 1] = newGrade;