Friday, 8 March 2013

Classes in Java

We said that one of the advantages of using Java as a programming language over C is its Object Oriented nature.In this tutorial lets see what it means to be an object oriented programming language. In this post we will see what are classes, what are objects and how they interact with each other.

What is OOP?

     OOP(Object oriented programming) means your program or code comprises of objects and these objects interact with each other to deliver the final result you are interested in.Why to program in an OOP language one might ask.Well, there are many advantages to use an OOP language over other languages. Some of them are Data Encapsulation, Polymorphism, Inheritance etc. These terms may sound a little advanced at this point of time but we will have separate posts of each of them.

    So lets get started with Classes and Objects.

Classes in Java

   Classes in java are nothing but blue print or templates for creating objects. Syntax for defining a class is

<AccessModifier> Classname
    member variable
    member functions

As  we had mentioned in post on Access modifier just recall that class level modifier are public and no modifier(default). So you can have only either public  as a access modifier or nothing  i.e just class. I would recommend just go through the access rules table Access Modifiers once again.
    Classname can be any name of your choice as long as it follows the naming rules.Take a quick look at the Naming Rules . Class definition must go inside curly braces following the class name. Inside these curly braces you must specify member variables Eg. private int count and member functions Eg. public int getCount() or public void setCount(int count).

Naming conventions for classes and its members

    There is a standard naming conventions that all Java programmers follow.These are not mandatory rules but some standards defined to make our lives easy.

Note  - A common convention for all is that try to give meaningful names relevant to your project or code.For example you are writing a program say to print "Hello World!", then you can have class name something like MyGreetings.
  • Package : If you don't know what a package is it is simply a directory or rather call it a structure which hols all your classes.It is recommended to make your our package and put your classes there than to use the default package.Package name must be entirely in lower case.
    Eg. package greeting or package com.javatutsforgeeks.greetings. For all your classes in a package must have first line as package packageName . If you are using an IDE like Eclipse or Netbeans you will automatically see it when you create a class inside a package. For others you have to manually specify.
  • Classes : Class names must be in Camel case.In Camel case all sub-words in a word start with an upper case.Also try giving name to your class which is a noun because a class represents an object in real world. Ex class MyGreeting .
  • Interfaces : Same convention as classes. Do not worry about interfaces for now.It's a very interesting topic and we will cover it soon after we learn inheritance. 
  • Members : Now when i say a member it can be a member variable or a member function. Conventions are same for both. Member name must start with a lowercase and starting letter of all subsequent sub-words are in capital letter.
    Eg. private String welcomeMessage or public String printGreetingd(String message).

Note : Your class name should be same as your file name in which you have your class. For example if your class is like public class MyGreeting then your file name should be Again an IDE will do this automatically for you but if you coding in some editor like notepad++ or vim then you must take care of this.

But i heard that we can have two classes in one file.What should we do in that case?

     Yes it is possible to have more than one class defined in a single file.In this case you must give file name same as the name of first class in your file.Though this is allowed it is strongly recommended to have one class per file.

Writing classes - Example

     Lets write complete code so that we understand classes completely once and for all.

package greetings;

public class MyGreetings {
    private String welcomeMessage;

    public String getWelcomeMessage() {
        return welcomeMessage;

    public void setWelcomeMessage(String welcomeMessage) {
        this.welcomeMessage = welcomeMessage;
    public static void main(String args[])
        MyGreetings greetings = new MyGreetings();
        greetings.setWelcomeMessage("Welcome to javatutsforgeeks!");

 Explaination - Above code defines a class called MyGreetings in a package called greetings. It has a member variable called welcomeMessage which is of type String and has access modifier as private. We then have member function which are nothing but getter and setter methods for our member variable welcomeMessage. Then we have out main() function which creates an object of our class MyGreetings, sets the value for member variable and prints it to standard output.

Quick Note : Since our member variable welcomeMessage is defined to be private we cannot access it using greeting. welcomeMessage and hence we have our getter and setter methods. This also forms a base for data encapsulation which we will study later.

Member variables and member functions

Member variable have the syntax 
AccessModifier variableType variableName;
Eg. private int count;
Member functions have the syntax
AccessModifier returntype functionName(arguments);
Eg. public void setCount(int count); 
 As stated earlier we have four member level access modifiers.Go through the post on Member level Access modifiers to review it once again.

We already know the Access modifiers and return types.Lets focus on arguments now.Arguments are parameters or variables that you want to pass to a function.These are local variables and their scope extend in the particular function only.You can pass as many arguments as you want.
Eg. public void setCountandName(int count,String name);
In Java we pass arguments as pass-by-value which means a copy of the reference to the object is passed.

Note : Java is pass by value! Java passes objects as references and those references are passed by value.

 We will see what are objects, how we create them in next post.This is one of the basic posts that forms the basis of other posts yet to come..Please let me know if you have any question.I will be more than happy to clarify them.

No comments:

Post a Comment

t> UA-39527780-1 back to top