Introduction to Java Objects

... by Bittle in Java Tutorial January 12, 2019

What is an Object?

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:

  • Color
  • Weight
  • Breed

Cat behaviors:

  • Eat
  • Meow
  • Nag

What an object can do we call methods, while an object knows about itself are called instance variables.

Whats the Difference Between a Class and an Object?

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.

Making Objects

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:

  1. Write Cat Class
  2. Write TestDrive class
  3. In your TestDrive class make a Cat object and access the variables and methods


Code

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();
    }
}


The Dot Operator (.)

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:

  • Test your real classes
  • Start you Java application

Comments (0)

Search Here