栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Object Basics: how OO works

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/885836.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号