Using Class in Java

In Java, a class serves as a template or blueprint from which individual objects derive. To craft a class in Java, one commences with the 'class' keyword, succeeded by the designated class name. It's customary for the class name to initiate with a capital letter, in line with Java's camel case naming convention. Enclosed within the curly braces of the class, one delineates data members and methods. These data members typify the attributes or state of an object, while methods encapsulate the behaviors or functionalities the object can execute. The accessibility of class members is governed by modifiers like 'public', 'private', and 'protected'. A member with 'public' access is universally accessible, 'private' confines its visibility solely within its parent class, while 'protected' allows visibility within its native package and its derivatives. For encapsulation, it's advocated to designate fields as 'private' and proffer 'public' accessor methods to manipulate these fields. The main method, articulated as 'public static void main(String[] args)', denotes the gateway for independent Java programs. Its existence signifies that the class is executable directly. In this Java Class Example, we've created a class enriched with a constructor and a method to produce output. Click Execute to run the Java Class Example online and see the result.
Using Class in Java Execute
public class Dog {
    private String name;

    public Dog(String name) {
        this.name = name;
    }

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

    public static void main(String[] args) {
        Dog myDog = new Dog("Buddy");
        myDog.bark();
    }
}
Updated: Viewed: 40 times