Java Objects and Classes tutorial


Java Object

An object has a state and behaviors. When we do software solutions with java, We use an object to model our problem. For a real-world example, we can think of a bird. A bird can fly so that a behavior. A bird has a color and a name. That is states.


Java Classes

A class in Java programming language is a template of something that will describe the behaviors (methods) and a state (fields) of that thing.

java objects and classes


Sample Java Class

public class Human {
    private String name;
    private int age;

    public Human(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void speak() {
        System.out.println("My name is " + name + " and my age is " + age);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Fields in the Java Class

Variables declared in a class but outside the methods called Fields. In this example, name and age are fields.

    private String name;
    private int age;


Constructors in the Java Class

Constructors are used to create objects. Constructors don't have a return type. The name of the constructor is equal to the class name but can have multiple constructors with different arguments.

   public Human(String name, int age) {


Methods in the Java Class

Methods in a Java class describes the functionality or behaviors of an object. You can use methods to perform some action on an object.

   public void speak() {
        System.out.println("My name is " + name + " and my age is " + age);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


<< Java Access Modifiers      Java abstract classes >>