Java objects are representations of real world objects. When thinking about objects note states and behaviors. For example, a Cat has different states and behaviors.
Cat states:
Cat behaviors:
What an object can do we call methods, while an object knows about itself are called instance variables.
A class is blueprint of an object. The class tells the virtual machine how to make an object of that type. You may define several objects from the class. For example, you might create 100 different dogs with a unique breed with the same class implementation.
We will create two objects: The object we want to test, and an object to test our main object. Let's make a Cat class to create several Cat objects which all have a meow method:
Cat.java
class Cat {
String name;
int age;
String color;
void meow() {
System.out.println("MEOWWW!");
}
}
TestDrive.java
public class TestDrive {
// main method! Everything starts here
public static void main(String[] args) {
Cat one = new Cat();
one.age = 90;
one.color = "White";
one.name = "Snowball";
one.meow();
Cat two = new Cat();
two.age = 1;
two.color = "Orange";
two.name = "Garfield";
two.meow();
Cat three = new Cat();
three.age = 2;
three.color = "Grey";
three.name = "Space Cat";
three.meow();
}
}
In the TestDrive example uses the period after the Cat object, but why? The period, called the dot operator, is used to access an object's state and behavior
The main method should only be used to: