How to Use Classes in Java | Object and Methods

This used to be one of those chapters that I used to dread. And there was no particular reason for that. “How to use classes in Java” more importantly how to be around one. I had a regular wont of quitting. I would lose interest and somehow run for my life. Because in my head I was convinced that Classes suck! And I don’t just mean only Java Classes by that.

But now that I am beginning to understand them (when I am all grown up mentally) I guess they aren’t really boring after all. They are serving a purpose and they are there to make life easier. Don’t trust me? Well, read on to find out.

What is a Class?

Before learning how to use classes in Java you must know what a class is. Look at a class as a template. Like something that allows you to associate similar things under one common roof. All those “things” are instances of it that carry similarities of one class.

staying awake in a java class meme

For example, Vehicle is a class. And instances of it are going to be cars, buses, trucks and so on.

Now that we have that out of the equation, let’s focus on learning how to use classes in Java.

Creating a Class and How to Use Classes in Java

This brings us to how do we create one in Java. Well, Java has syntax for everything.

Wo! I just figured out Java rhymes with Choco Lava. Tummy grumbles.

Alright, so the syntax for creating a class in Java is:

class ClassName {


        .......other stuff.......

}

where ClassName can be replaced by any name of your choice. Notice how the opening and closing braces follows the one common rule that we have been learning so far?

What opens, always closes. What has closed must have been opened.

Yes, you remember. Awesome!

Okay, so we are going to learn how to use classes in Java by actually writing this code in a piece of notepad so it would be learning on the go.

Step 1: Type the following in a notepad file:

example of a class named vehicle

We have just created a class called Vehicle. But doesn’t it feel kind of empty?

What does a Class Contain?

Now when I said other stuff, what are the things that comprise a class? A class can have plenty of things. I have slain all of them with bullets below:

  • Fields
  • Methods
  • Constructors
  • Blocks
  • Nested Classes
  • Interfaces

We are going to look at constructors, blocks, nested classes and interfaces in later chapters. We will focus on the stuff we are going to use right away that are going to help us in learning how to use classes in Java.

What are Variables?

A variable is nothing but a piece of memory that holds a data value.

There are two varieties of data types in Java:

  1. Primitive
  2. Non-Primitive (Reference Data Types)

Well, that might have forced you to wonder what data type is. Data type is nothing but a type that helps in the classification of data. As to how you would enter a name in your system. You name is full of alphabets right? So you are going to use char or String data type. If there’s a number involved, you will make use of int. etc.

While primitive data types only deal with storing the value, the non-primitive one stores both value and reference (address) to that value.

Examples of primitive data types are int, boolean, char etc.

While Non-Primitive data types can be an array, interface or a class.

NOTE: All keywords in Java (we have 50 keywords in total) starts with lower case.

Primitive Data Types

To learn how to use classes in Java we must know the crucial part of data types – primitive ones.

All data types in Java are keywords.

  • boolean                           True or False                             1 bit
  • char                                   Unicode character                  16 bits

Signed and Non-Decimal Values can be covered using:

  • byte                                  8 bits
  • short                                16 bits
  • int                                      32 bits
  • long                                  64 bits

Unsigned Values can be covered using

  • float                                  32 bits
  • double                             64 bits

NOTE: By default, every decimal value in Java is double.

So if we write:

float x = 32.35;

it will give you a compilation error.

To correct the above you need to strictly specify that you are using it as a float. Suffix the no. with an ‘f’ sign:

float x = 32.35f;

The error will be gone now.

Data type takes memory from Heap. It is advisable to use respective primitive data types to save memory. Like what’s the point of using int when you are dealing with numbers between -127 to 128?

We use operators to manipulate our primitive data types. Let’s understand about variable declaration and initialization properly before we understand how to use classes in Java.

Variable Declaration

In order to declare a variable you just have to provide a data type as a predecessor. Here we are declaring a variable called speed. We are using the data type as int which is nothing but a primitive data type that we had seen earlier, which deals with numbers.

int speed;

Variable Initialization

So far we have just declared the variable as int. But there’s no value to it. If there is no value provided the default value of data type is taken into consideration. The default value of int is 0. Hence the variable has been auto – initialized with the variable 0 so far.In order to initialize a variable we need to provide a value to it.

We will initialize it with a number of our choice. In order to initialize a variable we need to provide a value to it.

speed = 100;

We can choose to declare and initialize a variable in a single line of code as well. Combining the above two we will get:

int speed = 100;

So if we were to define a variable in our program this is how it would go:

example of a initializing a variable

Here speed is a variable and it has been initialized with a value 100. Here 100 is nothing but a Java literal. A Java literal is the syntactic representation of primitive data types. So for boolean the Java literals are going to be: true and false.

The above example creates a variable speed and allots the value 100 to it, however, Java doesn’t allot any memory to it just yet. It’s only during compilation that a memory slot gets created.

Instance Variable and Local Variable

Since we are using this one in a class it can be also called an instance variable. If we use it inside a method, constructor or a block the scope of it becomes limited or local. Such a variable is then called a local variable. Local variables should always be declared and initialized since there are no default values for them.

Remember this:

Member variable = Instance variable = Field.

They are all the same thing.

Default value of a reference variable is NULL. An example of reference variable would  be:

ClassName object = new ClassName();

where ‘object’ is the reference variable.

What is a Method?

A method is nothing but a function. Like what would a car do? Run? So there! Run is a method. What would it do then, I don’t know, stop? There you have another method.

The syntax to use a method is:

returntype methodName() {

...........define rest of the stuff here.......
}

Where you can replace methodName() with a method of your choice and return type is the form in which you want your output to be.

image of declaring methods in java

For our infamous example the methods are going to be:

Writing the above code will create two methods namely run and stop.

Notice how I have put in “void” in front of run and stop. Well void means that it doesn’t have a return type. You can alternatively use any data type there like int, boolean etc.

Okay, I am using simple display messages like “I am run” and “I am stop” so that when we call it later the result shows correctly.

What is an Object?

In order to learn how to use classes in Java we have to deal with the crux of a Class. It is nothing but an object.

Now as explained above, those instances that I was talking about, like cars, buses, trucks etc. are nothing but Objects. To define it we can say, an object is an instance of a class which sounds like a pretty cliched definition and it repulses me hearing it for the umpteenth time. Aaaarrrggghhh!

You can say an object helps in defining the behaviour of a class. We create an object so that interacting with methods, variables etc. can happen. We use them so that we could bring perspective to real life objects.

How to create an Object?

Creating an object isn’t that hard really. You have to remember a syntax that identifies with its class. The syntax to declare an object is:

ClassName object;

Now when you have declared it you need to instantiate and initialize it too. The syntax to do that is:

object = new ClassName();

Now to make the code look better and concise we can put all these steps in just one line:

Here goes it:

ClassName object = new ClassName();

You can see there are three parts to the aforementioned code namely:

  1. Declaration: It is the creation of the object named ‘object’ in the aforementioned saying that it is an instance of a class called ‘ClassName’.
  2. Instantiation: This is what happens when you use the keyword ‘new’ which is a Java operator that creates an object.
  3. Initialization: The final step is nothing but a call to the constructor.

You will learn about constructor at a later stage. Just know that it is like a method we call and has the same name as that of a class.

Breaking It Down

So basically the following things happen when you use the above-mentioned code:

  • Memory gets allocated to the object
  • Explicit attribute initialization happens if attributes are present (in the above case none)
  • Constructor gets executed
  • Object Reference is returned by the new operator
  • That object reference is then assigned finally to the variable

So if we take our program into account this is what creates an Object:

image of creating an object in Java

Here you can use any name instead of the word “object”. With the declaration (usage of new) some memory gets allocated to the word “object”. Now we are good to use this instance anywhere in our code.

Keep in mind that when you create an object, it basically creates a memory block, the reference to which is provided in the variable you create. Yes, you can display the information that has been put in your ‘object’ to see that it is nothing but some garbage value of a place in your system. Go ahead and display it using a simple System.out command:

System.out.println(object);

Remember there isn’t just one way to create an Object. I plan on writing all the ways to create an object at a later stage.

How do you call a Method?

When I say calling a method, I hope you are not actually calling a method like:

Psst. Hey! Hey! Method! Psst! Listen!

Imagine it as a portal that takes you to your method. So when you use the respective method name in your main function it will take you to your function.

Pay attention, because this is one crucial step in learning how to use classes in Java.

Now the one simple method to call a method via an object is by using the . (dot) operator. Simply use your object and follow it by a dot operator. Then immediately use the method name. That’s how you can use your object to call the first method in our code:

object.run();

Now the above code will force Java to teleport to the method named run(). It will execute whatever is in there, here “I am run” and then come back to the gates.

Similarly in order to call the second method you gotta use:

object.stop();

It will take you to the stop method and execute the method stop by printing “I am stop” and then come back.

This is how our code looks like now:

image of an object calling a method in java with dot operator

Note: Not only is the dot operator useful in accessing a method, but it is also useful in accessing a variable. You can use:

object.speed = 54;

in the above code to change the value in speed variable. See for yourself if things work. Go ahead and give that a shot.

Using the Inevitable Main Method

Our code wouldn’t run because there is no main method. So we will first go ahead and add one main method which will serve as the starting point for our JDK to look.

How do you do that? If you remember correctly from Chapter 2,  we used to use:

public static void main (String [] args) {
}

In this example we are going to use the main method inside the class Vehicle. Remember we can use it outside too. There’s no difference really. Here’s how our code should look like now:

when objects call methods inside a main function

So when you compile the code now, the focus first goes to main which then creates an object called object with the help of “new” keyword. It goes to object.run() and immediately searches for a method called run. It goes there executes whatever code is inside run method. Then it returns to the main method and navigates to the next line which is object.stop(). It will then force it to seek a method named stop().

Call Stack and Heaps

To understand how to use classes in Java and how method calling works first you need to understand some basics of memory allocation. There is a stack data structure mechanism that is being followed when JVM executes a call. Stacks basically hold method specific values that are short lived.

Au contraire there is Heap space which Java uses to allocate memory to Objects and Classes. So when you are creating an Object it’s actually getting created in Heap Space.

Stack stows values and references like a real stack, in a LIFO (Last in First Out) manner. When you call a method a new memory block is created in your stack memory. When the method ends, that block becomes unused and then becomes ready for a new method.

NOTE: Stack memory size is less compared to heap memory.

stack memory vs heap memory

Example to Fathom Method Calling

If there are multiple methods that are being called this is how things work in actuality, something that is kept hidden from the user. Let’s take a look at this example:

public static void main(String [] args) {

method1();
System.out.println("Back in main");

}

void method1() {

method2();

}

void method2() {

method3();
System.out.println("Method 2 says Bye");

}
void method3() {
System.out.println("We are in the final method");
}

So the call here goes something like this:

main() ---> method1() ---> method2() ---> method3() ---> "We are in the final method" ---> method2() ---> Method 2 says Bye ---> method1() ---> main() ---> Back in main

To represent the above in a pictorial diagram for stacks:

stack memory calling methods

That’s how it is going to work when you compile and execute it. How do you compile and execute? Well I was coming to it.

Compile and Execute

Go ahead save the file as Vehicle. java and then compile it by using the following code in your cmd:

javac Vehicle.java

When it gets successfully compiled execute it by typing:

java Vehicle

Did you get the expected result? I am getting the following result:

image you get after executing the program in cmd Java

You might have noticed how we didn’t use the field “speed” at all in our program. Feeling sorry for it? Okay just go ahead and put a code to display the speed after you are done calling object.stop().

image for trying to call a non-static field from a static method how to use classes in java

Save it compile it.

Did it work? No? Of course not. It wouldn’t.

When you try to compile it you will get a compilation error.

image for a compilation error for calling a non-static field from a static one

That’s because your main method is a static one. You can’t call a non-static field or a method from a static one. To do that you have to make it static.

Simply put the keyword static before the field speed like this:

image for making a field static in Java

When you are done save the field.

Once again navigate to cmd, compile and then execute.

You will get the final result as:

image for final result after running the code in Java

Are you confused with static and non-static? Don’t worry in the chapter about Static Classes I am going to clear that doubt once and for all.

So there! You have learned how to use classes in Java. Feel comfortable around them by creating as many classes as you want. Play around with methods.

If you keep at it, one fine day you are going to wake up and realize you have truly grasped how to use classes in Java, and how to be really comfortable around them.

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

10 Responses

  1. April 23, 2017

    […] It cannot access non-static data member or methods. So if you are planning on calling a non-static data member you must first make that data member static by using the static keyword like we did in the final part of Chapter 3. […]

  2. May 3, 2017

    […] any case you don’t understand the code, feel free to go back on how to create objects and classes and learn the basics […]

  3. May 11, 2017

    […] than it actually might seem. Now that we are already properly introduced to use of constructors and methods, understanding this java keyword would be like a walk in the […]

  4. June 1, 2017

    […] used to work in Java? Well if you don’t you can always flip through the pages and go back to this chapter to see how stack […]

  5. June 3, 2017

    […] The only absurd and unusual thing for you in the above syntax should be System.in. The rest of things, I am guessing, you already know about since we have been working on it for a while. If you still don’t know what they are, you can go back and check what’s what in the chapter about classes and objects. […]

  6. June 3, 2017

    […] are going to create two variables that will hold the numbers. Remember what you had learnt about data types? If you do, then you are going to walk right through it without realizing it was a big […]

  7. June 27, 2017

    […] That being said, we can declare and initialize an array it in a single line too just as we could do it for objects. […]

  8. November 22, 2017

    […] basics of Java to understand the what, and the why, you can always go back and flip our tutorial […]

  9. July 9, 2021

    […] – Function is similar to the concept of methods in Java. It is a code snippet you can use to call other functions or itself, or even a variable. You pass […]

  10. January 3, 2023

    […] We need to define it with some values inside. To do that we need to create a new object. Kind of similar to the concept of classes and objects in Java. […]

Leave a Reply