java class and java objects

Java class & Java Objects : A Master Guide

Java is an object-oriented programming language. In Java, there are objects everywhere. Objects are the core elements of Java, and class is the place where you describe the Java objects.

This guide contains the basics of Java class and Java objects you must learn as a Java beginner.

So, without further ado, let’s jump into the topic.

Previous Topic: Java Data Types

Next Topic: this Keyword in Java

Java Class and Java Objects

The relationship between class and objects in Java is very interesting and easy to figure out.

Let’s look into each of them in-depth.

Java Class

Java class is one of the non-primitive data types.

A class is the offactor of objects in Java. You don’t get it. Right? It is very simple. You create objects of a class in Java. Simple as that.!

java class concept

Class in Java is like a white paper. You write the characteristics of the object in your Java class and give it to the JVM. JVM process the information provided in the class and creates the object of the class for you at runtime.

Java classes are the places where you design your objects. Designing means specifying the object’s attributes, behaviors, .

Once you make the design of the objects in the class, you can create and use the objects.

Once you create objects, you can assign values to its properties. Each object can have unique property values. Like the Dogs Togo and Luna in the above image. Both the dogs are instances/objects of the class Dog. Hence, they have the same properties, but the value of each property is unique.

Java class and Java objects are like the mold of a cake and the actual cake. Cakes made using the same cake mold can be totally different. Right? They can have different ingredients, flavors, different prices, etc.

Like that, Class is the mold to create objects in Java.

java class is the mold of objects

Even if cakes or dogs have unique properties, they can also have some common attributes. Right? For example, all the dogs have four legs, all the cakes made using a single mold will have the same shape, etc.

You can specify these kinds of common properties of objects in the class as static. Check out the Java Variables guide to learn more about static variables.

You can create as many objects as you want, as long as there is enough memory to store the objects. There isn’t any limit to the number of objects you can create in Java.

no limit in creating java objects

Java objects are created in the heap memory. There are two types of memory that JVM uses while running a Java program. They are the Heap and the Stack. Java objects will always be stored in the heap memory, no matter whether you create the object locally or at the class level.

JVM uses the stack memory to store short-lived items like the local Java variables.

JVM stores the instance variables in the heap.

There is more to learn about heap and stack, which you will learn in another forthcoming guide.

To read more about the concept of Java classes, click here.

So, to create objects in Java first you need to create its class and define the object’s properties and behaviors inside the class, not outside the class.

In Java, you can’t write any program code outside the Java classes except a few items like the import statements, package declaration, enum declaration (enums are almost similar to Java classes, but not entirely. Enum is known as a special type of class in Java).

Note: You can learn everything about enum in the upcoming tutorials.

There are many predefined classes in Java. Some commonly used classes are String, System, Exception, etc.

Now let’s see the syntax to create a Java class.

How to Create Your Own Class in Java?

Creating a Java class is pretty simple.

  • First, you specify that it’s a class using the Java keyword class.
  • Second, give your class a logical name.
  • Third, give the open and close braces to denote the block/boundary of the class.
class Geeky {}

There are some naming conventions in Java for declaring classes.

  • The open brace should be in the same line as the class declaration statement (at the end)
  • There should be a blank space between the class name and the open brace
  • The close brace should show up right after the open brace if the class has nothing inside as you see above
  • The close brace should be indented to match the class declaration statement if the class contains something as you see below
class Geeky {
    // program statements
} //indented to match the class declaration

Now let’s create a class with some properties and behaviors (Behaviors = Methods in Java).

class Doggie {
	String name;
	String colour;
	float age;

	void barking() {
		System.out.println("Bow Bow Bow");
	}

	void running() {
		System.out.println("I am running now.!");
	}

	void eating() {
		System.out.println("Please Don't Disturb me. I am eating.!");
	}
}

You can add many data fields and methods inside a class. Are these the only things allowed inside a Java class?

What else can you add to a class in Java? Well, let’s look into that now.

Things You Can Have Inside a Java Class

In a Java class, you can have the following.

I have explained variables and methods in previous tutorials. You can read that by clicking the respective links given. I have explained about constructors in this guide below.

Let’s look at the next four items in brief now (Detailed explanation will be here in the forthcoming tutorials).

Nested Classes and Inner Classes

You can have classes inside a class in Java. Static classes inside a class are called nested classes and Non-static classes inside a class are called inner classes.

Nested Interfaces

Interface is a non-primitive data type, like Java class (will be covered in-depth in the next tutorial). Nested interfaces are the interfaces inside a class. Nested interfaces are static by default in Java.

Static Blocks

Static blocks are the blocks declared with the static keyword. You don’t have to specify a name to create a static block in Java. All you need to give is the keyword static and the open and close braces.

static {}

JVM will execute static blocks at first (even before the main method) when you run the program. Since a static block has no name to call, you cannot reuse it. You can have multiple static blocks in Java. JVM will execute them in the order you add them to the class.

class StaticBlocks {
    static {
        System.out.println("static block one");
    }
    static {
        System.out.println("static block two");
    }
    static {
        System.out.println("static block three");
    }
} 

Output:

static block one
static block two
static block three

You can use static blocks to initialize static fields in a Java class at the time of class loading.

Note: You will learn about class loading and class loaders in the coming tutorials.

Static methods are also examples of static blocks. You can call static methods as named-static-blocks because they have names to identify and call them.

Non-Static Blocks

Non-static blocks are the blocks that have only the open and close braces, nothing else.

{}

JVM executes non-static blocks right after you create an object of a class. Just like static blocks, you can have multiple non-static blocks in a class. You can use a non-static block to initialize the non-static fields of a class.

class NonStaticBlocks {
    {
        System.out.println("non-static block one");
    }
    {
        System.out.println("non-static block two");
    }
    {
        System.out.println("non-static block three");
    }
}

Non-static/Instance methods are also non-static blocks (named-non-static-blocks).

The difference between a block and a method is that the method has a name to call it.

Therefore, you can use a method (static or non-static) as many times as you want. But static and non-static blocks will be executed only once.

These are the items you can have in a Java class.

Now let’s learn more about the Java objects, how to create an object in Java, etc.

Java Objects

Java objects are the products or end-results of a Java class.

In the normal case, the purpose of creating Java classes is to create objects of the class and use the objects to perform the task you are trying to achieve using your Java program (even though there are exceptions to this like the use of abstract classes which is another topic we can discuss in another tutorial).

Java Objects are like building workers.

For example, imagine you are a contractor to build a building. So you assemble the workers, explain, and assign specific tasks to each worker. Now it’s the duty of the workers to take care of the rest.

Just like that, to perform a certain task in Java programming, you create and assign tasks to the Java objects. If you have given the instructions to the objects correctly, they will do their work the right way.

When the objects do that, the programmer gets the desired output.

The only difference is that in real-life you find the workers who are alive and who can do the task well. But in Java, you design your workers (objects) in Java classes and give life to them, which is the object creation.

So assume you have designed a class in Java. How do you create an object of the class?

How To Create Java Objects

In Java, you create objects using constructors.

Well, what is a constructor in Java?

Java Constructors

The Java Constructor is a block of code to construct Java objects. A constructor is like a Java method, but it is not exactly a method. Methods are used to define the behaviors of the object, and the constructor is the one that creates the actual object.

You can call it a special method. But I would suggest you call it constructor. Constructors are constructors. That’s it.

Java constructors have unique characteristics that make them “The object constructors“.

Characteristics of Java Constructors

1. The name of the constructor is the same as the class name

class Geeky {
    Geeeky() {} // constructor
}

2. In Java, every class will have a constructor, even if you don’t add one.

Default Constructor

Every Java class will have a constructor with it. This is called the default constructor. The default constructor is added by the Java compiler at the compile time. The default constructor is public and has no method parameters.

class Geeky {
    public Geeeky() {} // default constructor
}

Well, then what if you add a constructor?

Then the Java compiler will not add another constructor. The constructor you have added will be the only constructor in the class.

java default constructor creation scenarios

3. The constructor has no return type

The duty of a constructor is to create Java objects. It creates and assigns the object to the variable you declare. There is no point in adding a return type to the constructor because it’s not user-defined and anyway it will return the object and nothing else.

The program statements that create the object are not visible to the programmer. You just make a call to the constructor and Java takes care of the rest.

4. You cannot make a constructor static

Every static element of a Java class belongs to that class. You access them using the class name. Every non-static item in a class belongs to the objects of the class, and the constructor is the one who creates the objects. So it makes no sense in Java to have the option to make a constructor static.

5. You cannot call constructors like calling methods (Using the class name or object reference)

You cannot call it using the class name because you can call/access only the static items using a class name.

Using objects you can access only the non-static items in a class.

Constructors are neither of these.

Constructors are the creators of the Java objects. You must call a constructor for an object to be alive. And you can access the non-static items only if an object is alive. That’s why non-static elements in class are also called instance elements because they belong to the instances of a Java class (instance‘ is a term used to denote a specific object of a class in Java).

So when I say non-static variable or instance variable, I mean the same thing.

So how to call the constructor in Java?

In Java, there are two ways to call a constructor.

  1. Using the new keyword
  2. Using this() and super()
Call constructor using the new keyword

new is a Java keyword. The new keyword is used in Java to create new Java objects and also used to create new arrays (arrays are also objects in Java). The new keyword specifies you need a new object.

Now let’s create some objects with the new keyword.

First, let’s create a Java class named Geeky.

class Geeky {
    String name;
    String job;
}

Now I will add the main method and create a new object of the class Geeky.

class Geeky {
    String name;
    String job
    public static void main(String[] args) {
        Geeky geek = new Geeky(); 
    }
}

In the above program, I call the default constructor of the Geeky class with the new keyword.

Geeky geek = new Geeky();

Let’s break down the above statement.

1. new Geeky();

Here I call the constructor of the class Geeky with the new keyword. This statement creates a new object of the Geeky class. Geeky() is the call to the constructor. As I already mentioned, the class and the constructor has the same name in Java.

You cannot call the constructor without the new keyword. This is because the purpose of the constructor is to create new Java objects.

Geeky geek = Geeky();  This statement is wrong.

2. Geeky geek

This statement declares a variable of type Geeky. The class Geeky is the data type of the variable geek. Similar to the variables of the int, float, boolean, etc.

The difference is that int, boolean, and other primitive Java data types store the value, but the variable geek here stores the address/reference of the object’s memory location.

Because the variable stores the reference of the object, we call it the reference variable.

Don’t think of the variable geek as the object. It is not. It is the reference variable of the object that lets you access the object’s properties, methods, etc.

I suggest you read the Non-Primitive Java data types in the previous guide to get more understanding of this.

How to Access The non-static/instance elements of the class?

In Java, you access the elements of a class, interface, or package using the dot (‘.’) operator.

First, let’s create a method in the class to display the name and job of the Geeky and call the method.

class Geeky {
	String name;
	String job;

	public static void main(String[] args) {
		Geeky geek = new Geeky();
		geek.name = "Geeky"; // accessing the variable name and assigns the value 'Geeky'
		geek.job = "Blogger"; // accessing the variable job and assigns the value 'Blogger'
		geek.display(); // calling the instance method display()
	}

	void display() {
		System.out.println(name);
		System.out.println(job);
	}
}

Output:

Geeky
Blogger

In the above program, you can see that I access the two instance variables name and job and the method display() using the reference variable geek. Like this, you can use the reference variables (after assigning the object) to access any non-static elements in a Java class.

Only if the elements are accessible where you want to access them. This is because you can limit or increase the accessibility of the elements of a class in Java using the access modifiers (you will learn it in the later tutorials).

Let’s see another scenario.

If you create the Java object without a reference variable like below,

new Geeky();

Here, you just waste some memory. You won’t be able to use this Java object again. It’s like buying a phone and throwing it in the lake. You bought the phone, but you would never see that again.

Here is the importance of reference variables. A reference variable lets you use an object as many times as you want.

You can still create an object without assigning it to a reference variable, only if you are sure that you will need the object only once.

For example, imagine that you need to call the instance method display() of your Java class Geeky just once in your program. In that case, you can write like below.

new Geeky().display();

This is an okay statement because you don’t want to use the object anywhere else.

Note: You can access the instance elements of a Java class using the reference variable or by the object creation statement as above. These are just two different ways of doing the same thing.

Well, in the above example, you saw how to create an object using the new keyword.

Now let’s create multiple objects and learn a little more.

class Geeky {
	String name;
	String job;

	public static void main(String[] args) {
		Geeky geekyOne = new Geeky(); // first object
		geekyOne.name = "Geeky One";
		geekyOne.job = "Blogger";
		geekyOne.display();
		Geeky geekyTwo = new Geeky(); // Second object
		geekyTwo.name = "Geeky Two";
		geekyTwo.job = "Programmer";
		geekyTwo.display();
	}

	void display() {
		System.out.println(name);
		System.out.println(job);
	}
}

Output:

Geeky One
Blogger
Geeky Two
Programmer

In the above program, we have two objects, ‘geekyOne’, and ‘geeekyTwo’. The important thing you need to note here is that the objects have their own copy of the variables ‘name‘ and ‘job‘. This is true for all the Java objects. By copy, I mean different memory areas.

Java objects will get unique memory areas for the non-static variables in a class. Therefore, you can add or change the values of the variables of each object independently.

For example, If you change the name of the ‘geekyOne’ here, it won’t affect the name of the ‘geekyTwo’.

To understand a bit more, I suggest you read this.

In the above examples, I created the objects of the class Geeky inside the class. In Java, you can create objects of a class in any other Java classes, not just in the same class.

As long as your Java class is accessible to the other classes you can create objects of your class there.

Now, let’s create two Java classes and create the object of one class in the other class.

Class 1:

public class Website {
	String siteName;
	String niche;

	void display() {
		System.out.println(siteName);
		System.out.println(niche);
	}
}

Class 2:

public class Geeky {
	public static void main(String[] args) {
		Website site = new Website();
		site.siteName = "GeekyPoint";
		site.niche = "Java";
		site.display();
	}
}

Output:

GeekyPoint
Java

The above program has two Java classes with the names Website and Geeky, respectively. I created the object of the class Website In the Geeky class and assigned the string ‘GeekyPoint’ to the variable siteName and the string ‘Java’ to the variable niche.

Then I called the display() method of the Website class. The display() method prints the values of siteName and niche on the console.

Both classes are public. Therefore, you can access these classes from any other classes in your program.

Since these Java classes are public, they must be in their own source file with the source filename same as the class name.

Another important point you must note is that in Java, you can create n number of constructors. We call this constructor overloading.

Constructor Overloading

Constructor overloading means adding multiple constructors in a class.

The only condition when you overload constructors is that the signature of the constructors must be different.

For example, the default constructor has no parameters. If you explicitly add the default constructor in your Java class, then there should not be another constructor with zero parameters.

You can make different constructors by changing the type or number of the parameters different. For example, you can have a constructor with an int parameter and another one with a float parameter or two int parameters.

public class Geeky {

	public Geeky() {
		System.out.println("default constructor (no parameters)");
	}

	public Geeky(String name) {
		System.out.println("constructor with a string parameter");
	}

	public static void main(String[] args) {
		Geeky noParam = new Geeky(); // call the default constructor
		Geeky oneParam = new Geeky("Geeky"); // calls the constructor with one parameter
	}
}

Note: I didn’t add the default constructor in the other examples because the Java compiler will add it at compile time.

In the above program, I created two objects by calling the two different constructors of the Geeky class.

The primary purpose of having constructors with parameters is to initialize the instance variables at the time of object creation.

public class Geeky {
	String name;

	public Geeky() {
		System.out.println("default constructor (no parameters)");
	}

	public Geeky(String nameParam) {
		name = nameParam; // initializing the instance variable 'name' using the parameter 'nameParam'
	}

	public static void main(String[] args) {
		Geeky geek = new Geeky("Geeky"); // calls the constructor with one parameter
	}
}

In the above program, you can see that I passed the value ‘Geeky’ as the parameter value to the constructor in the main method. Inside the constructor, I assigned the parameter value to the instance variable ‘name‘. by doing this, you can skip setting values to the variables after the object creation.

Note: I will explain this() in the next guide, as it won’t fit in this guide. About the super(), It’s better to learn it after understanding inheritance in Java which you will learn after a few other topics here.

I suggest you read the guides Write Your First Java Program and Java Variables, where I talked about more points related to this guide.

Conclusion

These are the basics of the Java classes and objects.

Do you like this guide?

Did you know these points already, or are these completely new to you?

Let me know with a quick comment.

Hope you found this helpful.

Similar Posts

Leave a Reply

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