objects
class Song {
Song(String title, String artist) {
this.title = title;
this.artist = artist;
}
}
Java constructors share the class name
There is no constructor keyword
Syntax that looks like another language is a trap
That is the point of this chapter Syntax that looks like another language is a trap
this
this refers to the current instance
Use it when a parameter shadows a field
Without it the assignment does nothing
Immutable strings
String str = "hello";
str.concat("world");
Output:
hello
The original string does not change
concat returns a new string
For repeated building, use StringBuilder
Factory methods
List<Integer> nums = List.of(2, 5, 8);
List.of returns an immutable list
That is useful and surprising
Do not try to add to it
Next
Classes and inheritance in 04 classes
Posted