Java Classes

Classes, Objects and Methods in Java with Programming Example

In this chapter you will learn:Java Classes

  1. What are classes in java and how to create it?
  2. What is objects and how to initialize it?
  3. What is methods and how to create it?
  4. Programming Example
This is the very important chapter in java which enables you to make your own class, objects and methods. As you know java is object oriented programming language which means you can write program once and use it many times. The place where you write programming logic is class and when you use your program multiple times it is objects.

What are classes?

Classes are the blueprint of your program. It is the place where you define variables, methods, constructors, blocks, interfaces and program logic. Once classes are completed you can use it many times by creating its alias name or objects.

How to define class?

You can define class with class keyword as follow:

What is object and how to initialize it?

An object is an alias of the class which represents class behavior. A class may have many objects with different names. You can define objects as follow:

What is method or function?

A method of function is a basic building block of program which contains set of code and referred to by a name. A method is created inside class and can be accessed anywhere in program directly by name or followed by its class name.

How to define method?

It is very easy to define method in java. You can write method as follow:

OK. It’s enough for theory. Let’s understand all these concepts using programming example. In the following program we will create classes, methods and objects.

Programming Example:

Output

D:\JavaProgram>javac CreatingClass.java

D:\JavaProgram>java CreatingClass
Calculator Class Started…
PrintData Class Started..
30

D:\JavaProgram> __

Explanation:

In the above programming example we have done the following job.

  1. Created 2 separate class Calculator and PrintData.
  2. Calculator class have a method Add(int num1, int num2) which requires 2 integer number to process and it returns addition of both number.
  3. PrintData class have a method print(int value) which requires an integer value and print it on screen.
  4. In the main method I have created object of Calculator Class and send 2 integer value for processing.
  5. Next create object of PrintData and used it’s print method for printing output.

Summary

So, we have explained how to create classes objects and methods in Java. However there are lots of thing in classes but we can’t explain all those things here. It will make this article heavy for understanding. You will learn all those things part by part in the next few chapters. The next chapters explain Constructors in Java.



Leave a Reply

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