Creating Classes, Defining Attributes (Fields)

Learn how to create Java classes and define attributes (fields) with examples. Day 16 Java tutorial for beginners.
Creating Classes, Defining Attributes (Fields)

On Day 16, we learn how to create custom classes and define attributes (also called fields). Attributes represent the data that belongs to an object. Each object of a class can have different values for its fields.

1. Creating a Class with Fields


class Student {
    // fields (attributes)
    String name;
    int age;
    double grade;
}

Explanation: Here, Student is a class with three fields: name, age, and grade. These define the data a student object will hold.

2. Using Fields in Objects


public class Main {
    public static void main(String[] args) {
        // create object
        Student s1 = new Student();
        s1.name = "Alice";
        s1.age = 20;
        s1.grade = 8.5;

        Student s2 = new Student();
        s2.name = "Bob";
        s2.age = 22;
        s2.grade = 9.0;

        // access fields
        System.out.println(s1.name + " is " + s1.age + " years old with grade " + s1.grade);
        System.out.println(s2.name + " is " + s2.age + " years old with grade " + s2.grade);
    }
}

Explanation: Each object s1 and s2 stores its own values for name, age, and grade. Even though they are from the same class, their data is independent.

3. Default Values of Fields


class Example {
    int number;        // default 0
    boolean active;    // default false
    String text;       // default null
}

public class Main {
    public static void main(String[] args) {
        Example e = new Example();
        System.out.println("Number: " + e.number);
        System.out.println("Active: " + e.active);
        System.out.println("Text: " + e.text);
    }
}

Explanation: When no values are assigned, Java provides default values: 0 for numbers, false for booleans, and null for objects (like Strings).

Summary

Fields represent the data of a class. Every object created from a class has its own copy of the fields. Fields can be given values manually or use Java’s default values.

Post a Comment