Core Java Tutorial

 
 

Class

A class in java contains Variables and Methods, it is blueprint for the object.Each starting letter of the word in classname should start with capital letter(Ex: if your class name is firstjavacode then it should be like FirstJavaCode

   Ex:    public class FirstJavaCode{
          
            int a =10;// This is variable
            int b=20; // This is variable
            
            // now i am writing methods 
            
            public void add(){ 
            int c= a+b;
            }
            
            public void mul(){
            int c= a*b;
            }
         }

Object

Object is an entity which have states(variables) and behaviour(Methods). object is instance of class.

    Object creation syntax:

                      classname        objectreferencevariable = new classname();
                EX:   FirstJavaCode              fjc           = new FirstJavaCode();

Here you can use any name instead of objectreferencevariable. Here instantiation is achieved by using "new" keyword.if you use new keyword then JVM provides some memory to that particular objectrefencevariable(in our example JVM provides some memory to fjc), if incase if you use two new keywords to create object then JVM provides two separate memory area's.one of the main interview question is no of objects created below?

   Ex1:  FirstJavaCode fjc = new FirstJavaCode();
         FirstJavaCode fjc1 = new FirstJavaCode();
      Here i created 2 objects

   Ex2:  FirstJavaCode fjc = new FirstJavaCode();
         FirstJavaCode fjc = new FirstJavaCode();
      Here i created 2 objects

   Ex3:  FirstJavaCode fjc = new FirstJavaCode();
         FirstJavaCode fjc1 = new FirstJavaCode();
         FirstJavaCode fjc2 = new FirstJavaCode();
      Here i created 3 objects

i.e no of objects created is identified by no of new keywords.if we havee 2 new keywords then no of objects created are 2 ,if we havee 3 new keywords then no of objects created are 3.

Constructor

By default every class will have a constructor, i.e if you didn't create a constructor then JVM will create one which is default constructor.there are mainly two types of constructors are there

         1. default constructor

               Ex:        public FirstJavaCode(){
                           .......
                          }

         2. parameterized constructor
           
               Ex:        public FirstJavaCode(int a, int b){
                           ........
                           }
          

whenevr you create object, minimum one constructor should be invoke automatically.we need two keep mind 2 points while creating constructor

        1. constructor name should be same as class name.
        2. constructor did't retun any value i.e you must not use any retun type.

A class may have more than one Constructor i.e constructor overloading is possible in java