Unit 3 · OOP Concepts

3.1.2Attributes and methods

Java
public class Student {
    // attributes
    String name;
    int marks;

    // methods
    void display() {
        System.out.println(name + " scored " + marks);
    }

    String getGrade() {
        if (marks >= 75) return "A";
        else if (marks >= 65) return "B";
        else if (marks >= 50) return "C";
        else return "F";
    }
}

A method has a return type (void means it returns nothing), a name, a parameter list and a body.

Attributes in detail

An attribute is declared inside the class but outside every method. Every object gets its own copy, so two Student objects each have their own name and marks. If you do not give an attribute a value, Java gives it a default value:

Attribute typeDefault value
int, long, short, byte0
double, float0.0
booleanfalse
char'\u0000' (the null character)
Any object type, such as Stringnull (no object)

Local variables (variables declared inside a method) do not get default values. Using one before you give it a value is a compile error: variable total might not have been initialized.

Four kinds of variable

KindDeclaredBelongs toLives as long as
Instance variable (attribute)In the class, outside methodsEach objectThe object
Static variableIn the class, with staticThe class (shared)The program
Local variableInside a methodThat method callThe method call
ParameterIn the method's bracketsThat method callThe method call

Methods in detail

Java
String getGrade()                    // return type String, no parameters
void setMarks(int newMarks)          // returns nothing, one parameter
double average(int a, int b, int c)  // returns a double, three parameters

Inside a method you can use the object's attributes directly. display() uses name and marks without receiving them as parameters, because they belong to the object the method was called on.

Getters and display methods: a method that returns a value (such as getGrade()) lets other code use the result, for example to count how many students got an A. A method that only prints (such as display()) is useful for output, but its result cannot be used in a calculation. Prefer methods that return values, and print in one place.

Remember

  • Attributes hold the state of each object; methods define the behaviour shared by all objects of the class.
  • Attributes get default values; local variables do not.
  • Parameters are declared in the method; arguments are the values passed when calling it.