Java classes and Objects

In Java, a class is a template that defines the characteristics and behavior of an object. An object is an instance of a class, created at runtime based on the class definition.

Here is an example of a simple Java class:

public class Student { // class fields private String name; private int age; // class constructor public Student(String name, int age) { this.name = name; this.age = age; } // class methods public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } }

This class defines a Student object with two fields: name and age. It also has a constructor that allows you to create a Student object with a specific name and age, and four methods for getting and setting the name and age.

To create an object of this class, you can use the new operator and the constructor:

Student s1 = new Student("John", 20); Student s2 = new Student("Mary", 21);

You can then access and modify the fields of the object using the getter and setter methods:

s1.setName("Jane"); System.out.println(s1.getName()); // prints "Jane" System.out.println(s1.getAge()); // prints 20 s2.setAge(22); System.out.println(s2.getName()); // prints "Mary" System.out.println(s2.getAge()); // prints 22

This is just a simple example of how to create and use classes and objects in Java. You can find more information and examples in the Java documentation and online resources. 

Comments

Popular posts from this blog

Java GC and memory leaks, Thread and System performance