Classes and Objects in Java

Mannan Ul Haq
0

Java is an object-oriented programming language that offers robust support for classes and objects. A class in Java is a blueprint for creating objects that bundle data (attributes) and behaviors (methods). Now, let's explore the essentials of classes, objects, and access modifiers in Java.


Defining a Class in Java:

In Java, a class is defined using the keyword "class", followed by the class name. Inside the class, we can declare attributes (fields) and methods that operate on these attributes.

class Person
{
    // Attributes
    String name;
    int age;

    // Method to introduce the person
    void introduce()
    {
        System.out.println("Hi, my name is " + name + " and I am " + age + " years old.");
    }
}


In the above example, we define a class called "Person" using the class keyword. Inside the class, we have two attributes: name (of type string) and age (of type int). We also have a member method called introduce() which prints out the person's name and age.

Creating Objects and Accessing Members:

To create an object of a class, we use the "new" keyword followed by the class name and store it in a variable. Once an object is created, we can access its attributes and member methods using the dot operator (.).

class Main
{
    public static void main(String[] args)
    {
        // Creating objects of the Person class
        Person person1 = new Person();
        Person person2 = new Person();

        // Setting the attributes of person1
        person1.name = "Alice";
        person1.age = 25;

        // Setting the attributes of person2
        person2.name = "Bob";
        person2.age = 30;

        // Using methods to introduce the persons
        person1.introduce();
        person2.introduce();
    }
}

In the main() method, we create two objects of the Person class: person1 and person2. We then set the name and age for each person using the dot operator (.). Finally, we call the introduce() method on each object, which displays the person's information.

Access Specifiers:

Java provides access modifiers to control the visibility or accessibility of class members. There are four access modifiers:

1. `public`:

Public members are accessible from any part of the program. They have the widest scope.

2. `private`:

Private members are accessible only within the class where they are declared. They are hidden from other classes.

3. `protected`:

Protected members are accessible within the class where they are declared and its subclasses. (We will learn about subclasses in later tutorials)

3. `default (no modifier)`:

If no access modifier is specified, the visibility of a class, method, or field is considered as default. Default members are accessible within the same package.

Here's an example that demonstrates the use of access specifiers:

class MyClass
{
    public int publicVar;       // Public attribute

    private int privateVar;     // Private attribute

    protected int protectedVar; // Protected attribute

    int defaultVar;             // Default attribute

    // Methods can have any access modifier
    public void publicFunction()
    {
        System.out.println("PublicFunction: I can access all attributes.");
    }

    private void privateFunction()
    {
        System.out.println("PrivateFunction: I can only access the privateVar.");
    }

    protected void protectedFunction()
    {
        System.out.println("ProtectedFunction: I can access privateVar and protectedVar.");
    }

    void defaultFunction()
    {
        System.out.println("DefaultFunction: I can access all attributes within the same package.");
    }
}

NOTE: In a class, the default access specifier for its members is "default" (no modifier). This means that if you don't specify an access specifier for a member, it will be considered default by default. (alert-success)


Class Methods:

Class methods, also known as member functions, are functions defined within a class that operate on the class's attributes.


Classification of Member Methods:

In Java, methods can be classified based on their purpose and behavior. Three common types of methods are accessor methods (getter methods), mutator methods (setter methods), and utility methods.


1. Accessor or Getter Methods:

  • Accessor methods are used to retrieve the values of private attributes of a class.
  • Accessor methods provide read-only access to the private attributes, allowing other parts of the program to obtain the values.
  • Typically, accessor methods have a return type that matches the attributes they retrieve.

Example:


class Rectangle
{
    private double length;
    private double width;

    public double getLength()
    {
        return length;
    }

    public double getWidth()
    {
        return width;
    }
}


In the above example, `getLength()` and `getWidth()` are accessor methods that allow retrieving the values of the private attributes `length` and `width`, respectively.


2. Mutator or Setter Methods:

  • Mutator methods are used to modify the values of private attributes of a class.
  • They provide a way to update the internal state of an object by setting new values for the private attributes.
  • Mutator methods do not return a value (or return `void`), but they typically take parameters to update the attributes.

Example:


class Rectangle
{
    private double length;
    private double width;

    public void setLength(double Length)
    {
        length = Length;
    }

    public void setWidth(double Width)
    {
        width = Width;
    }
}


In the above example, `setLength()` and `setWidth()` are mutator methods that allow setting new values for the private attributes `length` and `width`, respectively.


3. Utility Methods:

  • Utility methods perform specific operations related to the class but may not directly manipulate the class's attributes.
  • They can be used for calculations, conversions, or any other functionality associated with the class.


Example:


class MathOperations
{
    public int Square(int number)
    {
        return number * number;
    }
}


In the above example, `Square()` is a utility method defined as a static member method. It calculates the square of a given number, but it does not require any access to the object's attributes.


Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !