Classes and Methods
Today we’ll be expanding on Java’s capabilities by introducing its object-oriented features.
By The end of this lesson you should:
So far we've used Java's provided types (e.g. String, Integer).
Now we will create our own objects to represent things that exist in our world
What if I want to represent a Person, who has a name, age and height?
We can do this in Java be defining a class - a blueprint from which we can create many Persons:
public class Person {
private String name;
private Integer age;
private Integer height;
public Person(String name, Integer age, Integer height) {
this.name = name;
this.age = age;
this.height = height;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public Integer getHeight() {
return height;
}
}
There's a few things going on, so we'll cover these step-by-step
public class Person {
...
}
This defines that we’re creating a new blueprint/class which defines a Person - it is public meaning anyone anywhere in another file can use this class.
public class Person {
private String name;
private Integer age;
private Integer height;
...
}
A field/property is a variable that belongs to the class - they are the internal state of the class.
In this case name, age and height are the state of a Person.
These properties are private to stop outside access and editing in ways we don't want.
Notice that we now cannot use var for properties.
public class Person {
// fields/properties
public Person(String name, Integer age, Integer height) {
this.name = name;
this.age = age;
this.height = height;
}
...
}
A constructor is the method used to create new Persons.
This method creates a new instance of Person and then lets us define what to do with the new instance
In this case name, age and height are initialized from the arguments of the same name.
Notice that we now cannot use var for arguments.
public class Person {
this.name = name;
// other fields/properties
// constructor
public String getName() {
return name;
}
// other methods
}
methods use the internal state of the object to return a result.
Methods are the only way you'll interact with objects, this lets the creator know that the internal state is always valid.