Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download PDF

How to create a class with methods and attributes in Java? Example Tutorial

Hello guys, we are again with new article that is on Creating Class with methods and attributes in Java. The main aim of this article is to give you idea about how to declare a class or method in Java and about different ways of declaring. In the world of Java programming, class serve as the fundamental building blocks for creating objects and defining the structure of your applications. These classes encapsulate data and behavior, allowing you to model real-world entities and implement the logic that governs their interactions.

At the heart of every class lies a carefully crafted combination of attributes (also known as fields or properties) and methods. Attributes represent the data associated with an object, while methods define the actions or behaviors that the object can perform. Together, they form the blueprint for objects that belong to a specific class.

In this article, we will embark on a journey to explore the art of creating classes in Java, complete with attributes and methods. 

Whether you are a Java novice looking to grasp the basics or an experienced developer seeking a refresher, you'll find valuable insights into crafting well-structured classes that power your Java applications. So, let's dive in and uncover the key concepts and steps involved in creating Java classes with methods and attributes.


What is a class in Java?

In Java, a class serves as a model or template for building objects. The attributes (also known as fields or variables) and the methods (also known as functions or operations) that describe how the objects made from the class behave are defined.
Example:

Here is an example of a straightforward Java class:

public class Student {

    // Fields or Attributes

    private String name;

    private int age;

    private double grade;



    // Methods or Operations

    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;

    }



    public double getGrade() {

        return grade;

    }



    public void setGrade(double grade) {

        this.grade = grade;

    }
}



In this example , the Student class has three attributes that correspond to a student's name, age, and grade: name, age, and grade. getName(), setName(String name), setAge(int age), getGrade(), and setGrade(double grade) are among the class's other methods. 

The get methods are used to obtain an attribute's value, whereas the set methods are used to give an attribute a value.

Now, let's see an example of how to create an object from the Student class and use its attributes
and methods:

public class Main {

    public static void main(String[] args) {

        Student student = new Student();

        student.setName("John Doe");

        student.setAge(25);

        student.setGrade(88.5);



        System.out.println("Name: " + student.getName());

        System.out.println("Age: " + student.getAge());

        System.out.println("Grade: " + student.getGrade());

    }

}




In this example , the set methods of the Main class are used to create a Student object and give its attributes values. Then, using the get methods, the values of the attributes are retrieved and printed to the console. 

It's also important to note that the Student class's attributes are marked as private, meaning that only other members of the class may access them. 

This is an illustration of encapsulation, a key idea in object-oriented programming that helps to safeguard an object's data and behavior. You must use the get and set methods to gain access to the private attributes from outside the class.


Class-Object Relationship

Understanding the connection between classes and objects is also crucial. A class defines an object creation process, but it is not an actual object. An object is an instance of a class, and each instance of a class has its own distinct set of values for the class's defined attributes.

One instance of the Student class, for instance, is the student object created in the Main class, which has its own particular set of values for the name, age, and grade attributes. If you make another student object, it will be distinct from the first student object and have its own set of values for these attributes.

You should be knowledgeable about a number of other crucial concepts in object-oriented programming, such as inheritance, polymorphism, and abstraction, in addition to classes and objects.
The ability to create a new class that inherits the properties and functions of an existing class is known as inheritance. 

This makes it simpler to manage and maintain your code because you can reuse and extend existing code. You can create code using polymorphism that interacts with objects belonging to various classes. 

A method that accepts an object of the Student class as a parameter, for instance, can also work with objects of other classes that derive from the Student class. The concept of abstraction is to hide a class's implementation specifics and only expose its behavior. 

Because you don't need to understand how a class operates internally, it is simpler to understand and use. 

The Student class in the preceding example is an illustration of abstraction because it hides the implementation specifics of how the values of the attributes are stored and changed and only exposes its behavior through the get and set methods.




Inheritance with example

Inheritance is a crucial component of creating a class in Java. A new class can be made based on an existing class and inherit all of its attributes and methods using the mechanism of inheritance. 

The inherited attributes and methods can then be added to or replaced by the new class to produce a customized version of the base class.


Example

The GraduateStudent class, which descended from the Student class and added the thesisTitle attribute, could be created.


public class GraduateStudent extends Student {

    private String thesisTitle;



    public String getThesisTitle() {

        return thesisTitle;

    }



    public void setThesisTitle(String thesisTitle) {

        this.thesisTitle = thesisTitle;

    }

}




In this illustration, the GraduateStudent class adds its own thesisTitle attribute and getThesisTitle() and setThesisTitle(String thesisTitle) methods in addition to inheriting all the attributes and methods of the Student class. 

Code reuse, ease of maintenance, and the ability to build a class hierarchy that reflects a real-world issue are just a few advantages of inheritance.



Polymorphism

Polymorphism is a crucial component of creating a class in Java. Due to polymorphism, you are able to refer to objects of various types using a single variable while calling the appropriate method according to the type of the object. 

Method overriding, which enables a subclass to provide a new implementation for a method inherited from its superclass, is used to accomplish this.


Example

To return the average of the student's grade and thesis grade, you could override the getGrade() method in the GraduateStudent class:

public class GraduateStudent extends Student {

    private String thesisTitle;

    private double thesisGrade;



    public String getThesisTitle() {

        return thesisTitle;

    }



    public void setThesisTitle(String thesisTitle) {

        this.thesisTitle = thesisTitle;

    }



    public double getThesisGrade() {

        return thesisGrade;

    }



    public void setThesisGrade(double thesisGrade) {

        this.thesisGrade = thesisGrade;

    }



    @Override

    public double getGrade() {

        return (super.getGrade() + thesisGrade) / 2;

    }

}



The getGrade() method of the Student class is overridden by the GraduateStudent class in this example to return the average of the student's grade and thesis grade. 

The super keyword is used to call the methods' implementation in the superclass, and the @Override annotation is used to indicate that the method is being overridden.

Here is another example of defining class hierarchies in Java using object oriented programming:


 



Conclusion

In order to build a hierarchy of classes using inheritance and polymorphism and to protect the data and behavior of objects, encapsulation is implemented along with the definition of attributes and methods. To write efficient and maintainable Java programs, it's imperative to comprehend these concepts. 

For Java object-oriented programming to be successful, it is crucial to comprehend inheritance, polymorphism, abstraction, and the relationship between classes and objects. Gaining familiarity with these ideas takes time and practice, but once you do, you'll be able to use Java to create programs that are more robust and scalable. 

In conclusion, one of the first steps in object-oriented programming is the creation of a class in Java. The attributes and methods that describe the state and behavior of objects derived from a class are defined by a class. 

The class can be used by making objects from it and then using the get and set methods or other class-defined methods to access their attributes and methods.


No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.