| English | 释义 | 拼音 |
|---|---|---|
| instance method/ˈɪnstəns ˈmeθəd/ | 实例方法 | shí lì fāng fǎ |
在对象上调用
- 实例方法用点记法在一个具体对象上调用。
word.length()对对象word调用length()。- 点之前的对象就是方法作用的那一个。
- 不同于类方法,你需要一个真实对象才能调用它。
对象就是上下文
- 在实例方法内部,代码处理的是那个对象的状态。
"cat".length()返回3;"hello".length()返回5——同一个方法,不同对象。- 方法读取(或改变)它被调用时所在对象的状态。
- 同一个类的两个对象,对同一个调用可以给出不同结果。

一个类对应多个对象:每个实例拥有各自独立的字段值
实参与返回值
- 实例方法可以接受实参并返回一个值,就像类方法一样。
"hello".substring(1, 3)传入1和3,返回"el"。- 接住返回的值:
String part = "hello".substring(1, 3); - 点的对象加上实参一起决定结果。
实例对类,并排看
- 类方法:
Math.sqrt(16)——点在类名之后。 - 实例方法:
word.length()——点在对象之后。 - 如果它需要某个具体对象的数据,就是实例方法。
- 如果它是一个不需要对象的通用工具,就是类(静态)方法。
**实例方法在点之前需要一个对象:word.length(),而非 String.length()。**点之前的对象提供方法作用的状态,所以同一个调用在不同对象上给出不同结果。类方法(Math.sqrt)改用类名——分清哪个是哪个,就知道你是否需要先有一个对象。
同一个方法,不同对象:
String a = "cat", b = "tiger";a.length()→3(作用于"cat")。b.length()→5(作用于"tiger")——点之前的对象决定。
实例方法用点记法在一个对象上调用(word.length());点之前的对象提供方法处理的状态。它像任何方法一样可以接受实参并返回一个值。这与在类名上调用的类(静态)方法(Math.sqrt(16))形成对比。
An instance method acts on its object
length() reads the state of the object before the dot.
Which is a correct call to the instance method length on a String word?
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Instance methods are called on an object: object.method().
What does "tiger".length() return?
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
"tiger" has 5 characters.
Math.sqrt(16) is a class method and word.length() is an instance method. The difference is...
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Class name before the dot → class method; object → instance method.
The same instance-method call can give different results on different objects.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
The object before the dot supplies the state.
An instance method is called on a specific ___ using dot notation (one word).
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
object.method() — the object supplies the context.