Classes and Objects in Java

What is a class ?

A class is basically a data structure or type inside which you can define some variables which are called member variables and methods which are called member methods.

The most important property of classes is you can create an instance or object from a class. so, you can maintain different states of a class using these instances or objects. So, let’s see how we can define a class which will be a new class and now we can use it with our main class


package example;
public class MyClass {

public static void main(String[] args){
Student joe = new Student(); //joe-> object or instance = 1; = "Joe";
joe.age = 20;

Student smith = new Student(); //smith-> object or instance = 2; = "Smith";
smith.age = 18;

System.out.println( + " is" + joe.age + "years old");
System.out.println( + " is" + smith.age + "years old");
package example;

public class Student {
int id;
String name;
int age;
Joe is 20 years old
Smith is 18 years old

An object is basically a collection of properties, which can be expressed as variables and functions, and with that collection of information, an object can represent some “thing”, whatever that “thing” is. So in this particular case the object called Student is representing Joe and Smith, but you can make an object so that it represents a particular person or dog , or anything else for that matter.

If you decide to represent a particular dog with an object called Tom just an example, you might have a different set of variables and a different set of functions to represent that dog.

So for example, you might still have “name”, but you might also have “breed” and “colour” and so on, and your object will probably have a different set of functions too, to show what kind of actions that dog can take. It could be for example like bark, jump, sleep or anything a dog might do.

I hope it will help you.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button