Lesson 15Creating Classes and Types
In this lesson, we'll look at how we define and create new types in Java and what comprises these new types.
CREATING NEW TYPES
Every time we define a new class in Java, we are defining a new type. As discussed earlier in the course, there are two categories of data types in Java: primitive types and reference types. New classes fall into the latter category.
Types (classes) in Java simply consist of fields (or properties) and behaviors (or methods). Fields and behaviors are sometimes referred to as members. You have already used several user-defined types, including Scanner
and String
.
Listing 15.1 presents a new class called Dog
. We could also say that Listing 15.1 is presenting a new type called Dog
!
LISTING 15.1
A New Class/Type Called Dog
public class Dog {
private String name;
private double weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public ...
Get Job Ready Java now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.