Java Class & Object Tutorial for beginners

Class is a template for creating objects which defines its state and behavior. A class contains field and method to define the state and behavior of its object. 

Syntax for Declaring Class:

<Access Modifier> class <Class_Name> extends
                 <Super_Class_Name> implements <Interface_Name>

ACCESS MODIFIER :  Defines who in the Java world can access this class and members of the class.

CLASS_NAME : Unique name for the class in a specific package.
SUPER_CLASS_NAME : Name of the class which given class extends.( extends keyword is used for this purpose)
INTERFACE_NAME : Name of an Interface which above class implements.( implements keyword is used for this purpose)

Internal structure of Class

<Access_Modifier> class <Class_Name> extends <Super_Class_Name> implements <Interface_Name>{
    <static initilizar block>
    <ananymous_block>
    <constructor_declarations>
    <field_declarations (Static or Non-Static)>
    <method_declarations (Static or Non-Static)>
    <Inner_class_declarations>
    <nested_interface_declarations>
    variables_inside_class(Static or Non Static)
}

Example of  Java Class

/*
 * This is Multi Line Comment and Comment can appear at any place
 */
package com.jbt;

import java.lang.*;

/*
 * As this file contains public class. Then the name of this file should be TestClass.java
 */
public class TestClass {
	public int i; // This is Non Static variable
	static {
		System.out.println("This is static block");
	}

	{
		System.out.println("This is ananuymous block");
	}

	TestClass() {
		System.out.println("This is constructor");
	}

	void methid() {
		System.out.println("This is method");
	}

}

class AnotherClass {
}

Classes are written in a Java source file. A source file can contain more than one Java Class. There are some rules associated to the Java source file as listed below.

Rules Applicable to Source file

  • There can be only one public class per source code file but it can have multiple non public classes.
  • In case there is any public class present in the source code file, the name of the file should be the name of the class.
  • Sequence of statements in a source code file should be package >> import  >> Class declaration.
  • No Sequence rule is applied for Comments. Comments can be there in any part of the source code file at any location.
  • Files with no public class can have any name for the class.
  • Import and package statements should be applied to all the classes in the same source code file.

Object

There is often confusion on the difference between Class and Objects. Class is the creation of a prototype and Object is the actual implementation of that prototype. Technically, Class is a template which describes what  state and behavior of an instance this class can have. Object implements the state and behavior in the form of variables and methods and requires some memory allocated.

How to Create an Object of a Class

To create an Object of  a Class <new> Keyword can be used.

Syntax:

<Class_Name>   ClassObjectReference = new <Class_Name>();

Here the constructor of the Class(Class_Name) will be executed and an Object will be created(ClassObjectReference will hold the reference of the created Object in memory).

Example

package com.jbt;

public class HelloWorld {
	int i; // Class Variable(State)

	void method() {
		System.out.println("Inside Method");
	}// Method (Behavior)
}

Object Create

HelloWorld obj = new HelloWorld();

How to Access the Member of a Class

(ClassObjectReference.member ). You will call the Method of an Object by naming the Object followed by a period (dot), followed by the name of the Method and its argument list.

objectName.methodName(arg1, arg2, arg3).

Bullet Points

  • Class can have only public and default access.
  • The public class needs to be in same name java file.
  • A single java file can contain more then one non public class but can have only one public class.
  • A public class can be seen by all classes from all packages
  • A class with default access can be seen only by classes within the same package.
  • A Java file with no public class have no naming restriction.
  • The Class can also have final, abstract and strictfp non access modifiers.
  • An Abstract Class can not be instantiated.
  • A Final Class can not be subclassed.
  • A Class can not be both final and abstract.
  • Class visibility can be seen in 3 parameter
    1. If a Class can extend another Class?
    2. If a Class can create instance of another Class?
    3. If a Class can access methods and variable of another Class?
Series Navigation<< jdk vs jre vs jvmConstructors in Java >>
By | 2017-08-14T10:52:10+00:00 April 19th, 2012|Core Java|41 Comments

About the Author:

41 Comments

  1. Java Dev February 7, 2013 at 11:39 am - Reply

    It will be great if you will underline the difference between the class and object. It’s very important for the beginner java developers.

    • Pushp Singh December 8, 2015 at 1:58 pm - Reply

      I am giving you a very basic and easy definition between class and object in java:

      1. “Class” in java can be assumed as any Infrastructure or building, and we create room
      withing that building to store our valuable, so this room can be assumed as “object.”
      2. Just like without building we cannot create rooms, like wise only without class we can
      not create object.
      3. Rooms are always inside the building, like wise objects are always inside the class.

      **** Now, coming towards accessing the objects:
      # There are 4 Access Specifier of any class:
      1. public 2. private 3. protected 4. default

      1. Any one can access to any rooms of the public building, like that only we can access
      objects of public class.
      2. Only the Residents can access to the room of the private building like wise only objects of
      private class are accessed inside the class only.
      3. If two friends are staying in one room of the same building and then after sometime one
      got shifted to another room of the same building, then there is a case that the guy who
      shifted to other room can have access to the another guy room, like wise only the object
      of the protected class can be accessed withing the same class as well as by all objects of
      that class.
      4. default class are known as “Package-private class” it is visible withing the same package
      only.

      • priya January 5, 2016 at 12:57 pm - Reply

        I didn’t get difference between default and protected

        • ganesh March 17, 2016 at 12:47 pm - Reply

          if u post a message or photo or video on u r time line
          in that case u will select “Privacy mode”
          i.e 1.if u select public ,u r post will all peoples are seen
          2. if u select private u only seen
          3.if u select protected u r friends(u r frnd list ) only seen

          • sushil March 20, 2016 at 11:23 am

            what about defult

          • J Singh March 23, 2016 at 3:09 am

            Default is access Modifier. You can get more detail about Access Modifier here.

          • jonesthomas February 3, 2017 at 5:13 am

            nice one thank you sir..

        • RAHUL SREEDHAR August 19, 2016 at 10:38 am - Reply

          protected can be accessed outside using child reference.but deafult cant

      • Kamlesh February 11, 2016 at 10:56 am - Reply

        Really Very Good definition….

      • Prabhu February 25, 2016 at 1:06 pm - Reply

        very nice explanation

      • nidhi March 4, 2016 at 7:28 am - Reply

        very well explained,awesome. Man you have very bright future.

      • santhosh November 22, 2016 at 12:32 pm - Reply

        thank u so much sir..i got a clear idea..:-)

  2. Usman Aslam February 26, 2013 at 6:31 am - Reply

    V good

  3. bhawna April 24, 2014 at 12:28 pm - Reply

    awesome…. its really good for beginners….

  4. […] be the same as the name given to the public class(For more details regarding class file rules click here). Once the file is saved open the command prompt and change its current directory to where the file […]

  5. shruti August 30, 2014 at 7:19 am - Reply

    The objects and class with example shud be mention, beginners don’t know about this and also explain what is n mean by instance of class

  6. puja September 6, 2014 at 8:16 am - Reply

    what main diff between class variable n classmethod

    • Vivekanand Gautam September 7, 2014 at 6:34 am - Reply

      Their is no link between these two. Variables & method are for two different purpose. Variables are to maintain state while methods are used to do some calculation or perform some business logic.

      Thanks

  7. Balan January 14, 2015 at 3:17 pm - Reply

    In the introductory para you have said: “In case there is any public class present in the source code file, name of the file should be the name of the class”. Does this mean ( pl see ” In case”) there can be a source code without public class? If so, the file name can be that of any class in the package or any other name also ?

    • Vivekanand Gautam January 24, 2015 at 6:16 am - Reply

      Yes. A file can exist without any public class. But if there is a public class file name should match with same.
      In this way you can have more than one public class in a file.

      Thanks

  8. meka jagadeeesh reddy May 1, 2015 at 1:38 pm - Reply

    excellent answers

  9. Ysatishkumarreddy July 30, 2015 at 8:20 pm - Reply

    Thank you

  10. ms08 August 31, 2015 at 3:09 am - Reply

    It’s great. Good article

  11. c manju November 13, 2015 at 6:03 am - Reply

    please explain all concepts with examples and explanantion…

    • J Singh November 13, 2015 at 6:33 am - Reply

      What information you are looking for??

      • Priya December 7, 2015 at 6:03 am - Reply

        Claases and Methods in classes with example,how they can be used.and objects with an example.

  12. Venkat December 13, 2015 at 5:26 pm - Reply

    Very good

  13. Madhavi December 16, 2015 at 7:39 am - Reply

    In Bullet Points….. “An abstract class cannot be initiated” it should be “An abstract cannot be instatiated”…. please verify it

    • Madhavi December 16, 2015 at 7:40 am - Reply

      “An abstract class cannot be instantiated”

  14. as January 23, 2016 at 10:58 am - Reply

    full description

  15. Devi Lanka February 11, 2016 at 10:54 am - Reply

    Its verry usefull for java biggeners.Thanks alot……….

  16. Praveen Sangati May 5, 2016 at 8:54 am - Reply

    need little more deep explanation, using real time coding.

  17. neha agarwal May 21, 2016 at 3:26 am - Reply

    I m not understand about jbt . how it is used and install

    • J Singh September 3, 2016 at 10:18 am - Reply

      jbt is short form of javabeginnerstutorial

  18. Sarang December 4, 2016 at 12:09 pm - Reply

    ‘Class_name, Super_Class_Name, Interference_Name’, Can someone explain it in detail.
    What’s the diff between extends and implements.

    • J Singh December 25, 2016 at 6:38 pm - Reply

      Hi Sarang,
      As the name suggest, when you want to extend(or change) the behavior of class you will use “extend” keyword with given class. And implement is used when you are going to implement the behavior, which is the case in Interface.

      Regards

  19. Mayuri Mittal January 16, 2017 at 12:33 pm - Reply

    Hi,

    A class with default access can be seen only by classes within the same package.
    Can you please explain what this line means..

    Class Java(){} Is this class considered as default or non public.

    • J Singh January 22, 2017 at 7:56 pm - Reply

      I really don’t know what you mean by Non Public. If you are not using any Access Modifier against class name it will be treated as Class with Default Access modifier. And given class is having default AM. And as it is having a default AM it means all the class in same package(It is different from same java file) can access given class. In order to understand please read about Package also.

      Regards

  20. Sharma January 19, 2017 at 11:34 am - Reply

    Thank You sir

  21. venkat May 8, 2017 at 1:07 pm - Reply

    AWESOME..Thank you Beginnerstutorial,,,Thanks lot.

  22. Anurag Singh July 28, 2017 at 11:04 am - Reply

    This is awesome post about object and class in java.
    keep posting for us.
    thanks

Leave A Comment