Java Classes and Objects
A class is a blueprint that describes the fields of a kind of thing. An object is one instance built from that class.
Create an object and read its field
new Dog() builds one Dog object. The dot in dog.name reads the name field through the object.
class Dog {
String name = "Buddy";
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
System.out.println(dog.name);
}
}Two objects share the same default
Both objects come from the same class. Each one starts with the field value written in the class.
class Dog {
String name = "Buddy";
}
public class Main {
public static void main(String[] args) {
Dog first = new Dog();
Dog second = new Dog();
System.out.println(first.name);
System.out.println(second.name);
}
}Use a field in a line of text
The field value joins a label in one print line. The output shows the stored name after the label.
class Dog {
String name = "Buddy";
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
System.out.println("Name: " + dog.name);
}
}Example
class Dog {
String name = "Buddy";
}
public class Main {
public static void main(String[] args) {
Dog first = new Dog();
Dog second = new Dog();
System.out.println("First: " + first.name);
System.out.println("Second: " + second.name);
}
}Key points
- The class keyword starts a class declaration.
- A field is a variable declared inside a class.
- The new keyword creates an object from a class.
- A dot reads a field through an object.
- One class can build many objects.
- Each object is a separate instance of the class.
In this example, the Dog class declares one field named name. The main method builds two Dog objects from that class. Each print line reads the name field through one object, and both objects show Buddy.
Note
Only one class in a file can carry the public marker, and that class is Main.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the new keyword do?