Objects in Java
An object in Java is a runtime instance of a class. It holds the state of all fields declared in that class. A Java object is created by using the keyword new. The new keyword tells the Java Virtual Machine to allocate space for the size of the data type being declared and store it on the Heap. We will discuss different data types in a later blog along with the Java Virtual Machine(JVM). Below is a simple example of creating a runtime instance of a Dog class.
public class Dog { private String name; // Sets the name of a dog public void setName(String name){ this.name = name; } // Gets the name of the dog public String getName(){ return name; } public static void main(String args[]) { // Instantiates a new Dog Objects Dog dog = new Dog(); // this is a runtime instance of the Dog class (Dog Object) // Calls the setName method of Dog to set the dogs name dog.setName("Sparky"); // Prints out the name of the dog to the console by calling getName(); System.out.println(dog.getName()); } }