简体   繁体   中英

Confusion when returning objects

public class MyString {
//instance variables
char[] charArray;
public MyString(char[] chars) {
    charArray = new char[chars.length];
    for (int i = 0; i < chars.length; i++) {
        charArray[i] = chars[i];
    }
}

public MyString print() {
    for (int i = 0; i < charArray.length; i++) {
        System.out.print(charArray[i]);
    }
    return new MyString(charArray);
}
class MyStringClient {

public static void main(String[] args) {
    MyString str1 = new MyString(new char[] {'h', 'a', 'p', 'p', 'y'});
    str1.print();

}

}

Hello, I have a question about how the code works. In my book it wanted me to make my own implementation of the string class. I made a class called myString and a class called MyStringClient to test it. There are no issues with the code, it outputs "happy" when executed but I got it to work by just experimenting if that makes sense. When I went back and tried to understand what I did a little better, I was confused on how my print function works in the MyString class. My book told me to make the method of type MyString and so I returned a MyString object, however if I make a reference variable to any normal object and try to System.out.print(obj ref var), I get some hashcode value. How is it this function is able to display the actual content of the object, I'm confused. Thanks.

Your public class MyString contains a public function print which returns a MyString type.

By creating a str1 MyString variable
MyString str1 = new MyString(new char[] {'h', 'a', 'p', 'p', 'y'});
MyString now contains a char[] called charArray.

Lastly you're calling the print function on that same MyString object.

That print function on your str1 MyString object:
for (int i = 0; i < charArray.length; i++) {
        System.out.print(charArray[i]);
    }

simply prints out each entry in the charArray you populated above with:
new char[] {'h', 'a', 'p', 'p', 'y'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM