gpt4 book ai didi

java - 使用对象引用变量调用方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:24:49 25 4
gpt4 key购买 nike

我在 SCJP 书中阅读了一个序列化示例。下面我发布了该示例源代码

import java.io.*;
public class SerializeDog {
public static void main(String[] args) {
Collar c = new Collar(3);
Dog d = new Dog(c, 5);
System.out.println("before: collar size is "+ d.getCollar().getCollarSize());
try {
FileOutputStream fs = new FileOutputStream("testSer.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(d);
os.close();
}catch (Exception e) {
e.printStackTrace();
}
try {
FileInputStream fis = new FileInputStream("testSer.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
d = (Dog) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("after: collar size is "**+ d.getCollar().getCollarSize());**
}
}

class Dog implements Serializable {
private Collar theCollar;
private int dogSize;
public Dog(Collar collar, int size) {
theCollar = collar;
dogSize = size;
}
public Collar getCollar() {
return theCollar;
}
}

class Collar implements Serializable {
private int collarSize;
public Collar(int size) {
collarSize = size;
}
public int getCollarSize() {
return collarSize;
}
}

我想知道当我们调用 d.getCollar().getCollarSize(); 时执行了哪个方法...请解释一下在 java 中这是什么类型的方法调用。我们如何使用这样的两种方法。

最佳答案

i want to know when we call d.getCollar().getCollarSize(); which method gets executed...

JAVA 在对象 d 上调用/执行 gettCollar(),并返回 Color 的实例。 getCollarSize() 将在 d.getColor() 方法返回的 Collar 实例上调用。

这就是我们如何链接方法调用。

您可以将方法调用分成两步

Collar collar = d.getCollar();
int collarSize = co.getCollarSize();

关于java - 使用对象引用变量调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22980170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com