A class is a blueprint that defines the variables and the methods common to all objects of a certain kind. Simply, a blueprint for creating objects.
Objects have two major characteristics, the state, and behavior. A programming language object stores its state in fields(variables) and executes their behavior with methods.
As you know, a class provides the blueprint for objects. you create an object from a class, and the object is an instance of a class
People tim = new People();
tim is an instance
Lastly, A reference is an address that indicates where an object’s variables and methods are stored.
Class People
package sample;
public class People {
private String name;
private int age;
// Create Constructor
public People(String name, int age) {
this.name = name;
this.age = age;
}
public String move() {
return this.name + " is moving";
}
/**
* @return String return the name
*/
public String getName() {
return name;
}
/**
* @return int return the age
*/
public int getAge() {
return age;
}
}
Instances of the People Class in Main Class
package sample;
public class Main {
public static void main(String[] args) {
People tim = new People("Tim", 45);
People mike =new People("mike", 30);
System.out.println(tim.getName());
System.out.println(tim.getAge());
System.out.println(mike.getName());
System.out.println(mike.getAge());
}
}
A class People with instance variables (fields) name and age. In the Main Class, we create tim and mike objects which are instances of the people class.
the tim and mike objects are a reference to the object in memory.
People tim = new People("Tim", 45);
People myfriend = tim
If we assign a myfriend and defined as tim, the reference of myfriend and tim is the same. we have two references pointing to the same object in memory.
*An instance variable is a variable which is declared in a class but outside of constructors, methods, or blocks.
In java you have references to an object in memory, there is no way to access an object directly. Everything is done with a reference.