Attributes:Attributes represent the state of an object.
There are 2 main types of attributes: – Instance variables – Class variables
method return; must be of same type as returnType – not needed if void
Important: A method uses parameters, (void go(int z))whereas the caller passes arguments(p.go(x))
Using instance variables and methods:
General rules:
– to access a (public) instance variable v of an object o, we reference it using the dot notation: o.v
– to invoke a (public) method m of an object o, we also reference it using the dot notation: o.m()
A constructor is a special method, with same name as the class name, used for initialisation.
– A constructor always has the same name as the class.
– It does not have a return type, not even void!
– An empty no-argument constructor is provided for you by Java.
Constructors may have parameters if you write your own.
Data Encapsulation:
An object should be selfgoverning (or work by itself).
• We should NOT allow direct access to an object’s variables.
• Any changes to the object's state (i.e. its variables) should be made ONLY by that object's methods
• Give "private" access
public->protected(package and other class which etend it)->deflaut(package members)->private(class only)
For "private",we should use accesser(get) and mutator(set) method
public void setName(String name) {
this.name=name //name refers the varianle passed and this.name refers the instance variable(Attritube)
}
Using accessor (or getter) and mutator (or setter) methods is always preferable to declaring things as public.
All getters and setters should have names that conform to the following:
variableType getVariableName() void setVariableName(VariableType)
Instance and Local Variables
• Instance variables are declared inside a class but not inside a method. – are initialised to the default value; – are valid (or have scope) throughout the entire class.
• Local variables are declared within a method. – are NOT initialised to the default value, and so must be initialised. – have scope only within that method!
Method parameters and local variables … public void doIt(int b)
• Method parameters are virtually the same as local variables! – They are declared inside the method. – They are valid (or in scope) only inside the method. – They are always initialised (by the caller of the method).
构造方法和set方法都可以传参
在构造方法中可以使用this.setName(Name),减少修改代码的次数