Class Structure

 

Python

Java

 

Class definitions have the general form

 

class <name>(<superclass name>):

 

    <class variables>

 

    <class methods>

 

    <instance methods>

 

 

 

 

 

 

The parenthesized superclass name is omitted for basic classes.  Items within the class definition can appear in any order.

 

Example:

 

class Student:

 

    NUM_GRADES = 5

 

    def __init__(self, name):

        self.name = name

        self.grades = []

        for i in range(Student.NUM_GRADES):

            self.grades.append(0)

 

    def getName(self): return self.name

   

    def getGrade(self, i):

        return self.grades[i – 1]

 

    def setGrade(self, i, newGrade):

        self.grades[i - 1] = newGrade

 

    def __str__(self):

        """Format: Name on the first line

        and all grades on the second line,

        separated by spaces.

        """

        result = self.name + '\n'

        result += ''.join(map(str, self.grades))

        return result

 

 

 

 

 

 

 

 

 

 

Usage:

 

s = Student('Mary')

for i in range(1, Student.NUM_GRADES + 1)

    s.setGrade(i, 100)

print s

 

 

Class definitions have the general form

 

<visbility modifier> class <name> extends <superclass name>

                                  implements <list of names>{

 

    <class variables>

 

    <class methods>

 

    <instance variables>

 

    <instance methods>

 

    <inner classes>

}

 

Classes that do not explicitly extend another class extend the Object class by default.  A class may implement zero or more interfaces.

 

Example:

 

public class Student{

 

    public static final int NUM_GRADES = 5;

 

    private String name;

    private int[] grades;

 

    public Student(String name){

        this.name = name;

        this.grades = new int[NUM_GRADES];

    }

 

    public String getName(){

        return this.name;

    }

   

    public int getGrade(int i){

        return this.grades[i – 1];

    }

 

    public void setGrade(int i, int newGrade){

        this.grades[i - 1] = newGrade;

    }

 

    public String toString(){

        /*

        Format: Name on the first line

        and all grades on the second line,

        separated by spaces.

        */

        String result = this.name + '\n';

        for (String grade : this.grades)

            result += grade + ' ';

        return result;

    }

}

 

Usage:

 

Student s = new Student("Mary");

for (int i = 1; i <= Student.NUM_GRADES; i++)

    s.setGrade(i, 100);

System.out.println(s);

   

 

 

Previous

Index

Next