codegurukool.com · Free coding tutorials & online compiler

Home › Java Tutorial › Java classes and objects

Java classes and objects

Blueprints and the things built from them.

A class describes fields (data) and methods (actions). new creates an object. A constructor has the class name, no return type, and runs when the object is created. this refers to the current object.

Example code

class Dog {
  String name;
  int age;

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

  void bark() {
    System.out.println(name + " says Woof");
  }
}

public class Main {
  public static void main(String[] args) {
    Dog d = new Dog("Rex", 3);
    d.bark();
    System.out.println(d.age);
  }
}

Run this code in the online editor

← Java method overloadingJava static members →