Java Classes and Objects
So far your programs used one class, Main, mostly as a container for methods. Java is an object-oriented language, and its real strength is that you can make your own types. A class is a blueprint that describes a kind of thing: what data it has and what it can do. An object is one concrete thing built from that blueprint. String is a class, and every piece of text is a String object.
Your first class
A class describes fields (the data each object holds) and methods (what each object can do). The keyword new creates an object:
class Dog {
String name;
int age;
void bark() {
System.out.println(name + " says woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog rex = new Dog();
rex.name = "Rex";
rex.age = 3;
Dog bella = new Dog();
bella.name = "Bella";
bella.age = 5;
rex.bark();
bella.bark();
System.out.println(bella.name + " is " + bella.age + " years old.");
}
}Rex says woof! Bella says woof! Bella is 5 years old.
class Dogdefines the blueprint. It is notpublic, so it can share the file withMain.new Dog()creates a new object, and the variablerexholds a reference to it.- The dot reaches an object's fields and methods:
rex.name,rex.bark(). - Notice that
barkhas nostatic: it belongs to each object and uses that object'sname.
Each object has its own copy of the fields: changing rex.name does not change bella.name.
Objects are references
Like arrays, objects are reached through references. Assigning one object variable to another copies the reference, so both point to the same object:
class Counter {
int value;
}
public class Main {
public static void main(String[] args) {
Counter a = new Counter();
Counter b = a;
b.value = 10;
System.out.println(a.value);
Counter c = new Counter();
System.out.println(c.value);
System.out.println(a == b);
System.out.println(a == c);
}
}10 0 true false
A new object's number fields start at 0, its booleans at false and its references at null.
Classes in their own files
In real projects each class lives in its own file named after it. Our editor works the same way: this example has two files, and Try it in the editor opens both. When you press Run, the editor compiles all the files together.
public class Main {
public static void main(String[] args) {
Book b = new Book();
b.title = "Wings of Fire";
b.pages = 180;
b.describe();
}
}public class Book {
String title;
int pages;
void describe() {
System.out.println(title + " has " + pages + " pages.");
}
}Wings of Fire has 180 pages.
Setting fields one by one after new is clumsy and easy to forget. The next topics show better ways: Class Attributes, Class Methods and Constructors.
Practice exercises
- Write a class
Carwith fieldsbrandandspeed, create two cars and print them. - Add a method
accelerate()toCarthat adds 10 tospeed, call it twice and print the speed. - Create a
Studentclass in its own file with anameand amarksfield and a method that prints whether the student passed (marks of 40 or more).