Object Basics: how OO works

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),减少修改代码的次数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值