☰ Topics

Classes and Objects


We have already discussed about the theory of classes and objects. Let us illustrate it with the help of program.

A class is declared by the use of class keyword.

Syntax:-

class <classname>
{
    <type> <instance-variable1> ;
    <type> <instance-variable2> ;
    .
    .
    .
    <type> <instance-variableN> ;

    <access-specifier> <returntype> <method1>([parameter-list]) 
    {
        //body
    }
    <access-specifier> <returntype> <method2>([parameter-list]) 
    {
        //body
    }
    .
    .
    .
    <access-specifier> <returntype> <methodN>([parameter-list]) 
    {
        //body
    }
}
                        

Here, the variables are refered as instance variable because each instance of the class contains its own copy of these variables. Therefore, the data for one object is seperate and unique from the data for another. The instance variables are acted upon and accessed by the methods defined for that class. We can say that it is the methods that determine how a class' data can be used. The methods and variables defined within a class are members of the class.

Creating Objects:

We need to create object in order to access the members of the class. The process of creation of object is called instantiation.

Syntax:-
<classname> <objectname>=new <classname>();
                        

Here, the classname is the name of the class, object name is the name of the object. new keyword is used to intantiate the object i.e. space is allocated in memory and returns a reference to it. classname() is the default constructor that is used to initialize the instance of the object. The default constructor is created and is automatically called.

Methods:

We have used many pre-defined methods till now. Methods can also be user-defined i.e. its functionality is defined by the users.

Syntax for defining a method:-
<access-specifier> <returntype> <methodN>([parameter-list])     //Function Signature
{
        //definition(process area)
}
                        

access-specifier can be public, private or protected which determines from where the method can be accessed(Discussed later in detail). Return type determines whether the method is returning value or not. method name can be any valid identifier and parameter list is optional. This whole line is called function signature.

Different ways of function signature:

  • no parameter no return
  • no parameter with return
  • with parameter with return
  • with parameter no return


Examples:

  • no parameter no return
    class exfun1
    {
    	public void add()   //Non-static function, object is needed to call
    	{
    		int num1=5,num2=6;   //input
    		int sum=num1+num2;   //processing
    		System.out.println("Sum="+sum);  //output
    	}
    	public static void main(String[] arg)
    	{
    		exfun1 ob=new exfun1();  //creation of object
    		ob.add();  //invokation of function, dot is a referential operator used to call members of class
    	}
    }
                                        

    OUTPUT:
    
    E:\java\new_java>javac exfun1.java
    
    E:\java\new_java>java exfun1
    Sum=11
                                    
  • no parameter with return
    class exfun2
    {
    	public int add()   
    	{
    		int num1=5,num2=5;   
    		int sum=num1+num2;   
    		return sum;   //value of sum is returned to calling function i.e. main()
    	}
    	public static void main(String[] arg)
    	{
    		exfun2 ob=new exfun2();  
    		int sum=ob.add();   //value returned from the called function is stored in sum
    		System.out.println("Sum="+sum); 
    	}
    }
                                        

    OUTPUT:
    
    E:\java\new_java>javac exfun2.java
    
    E:\java\new_java>java exfun2
    Sum=10
    
  • with parameter with return
    class exfun3
    {
    	public int add(int num1,int num2)   
    	{  
    		int sum=num1+num2;   
    		return sum;   //value of sum is returned to calling function i.e. main()
    	}
    	public static void main(String[] arg)
    	{
    		exfun3 ob=new exfun3();  
    		int sum=ob.add(7,5);   //value returned from the called function is stored in sum
    		System.out.println("Sum="+sum); 
    	}
    }
                                                                       

    OUTPUT:
    
    E:\java\new_java>javac exfun3.java
    
    E:\java\new_java>java exfun3
    Sum=12
                                    
  • with parameter no return
    class exfun4
    {
    	public void add(int num1,int num2)   
    	{  
    		int sum=num1+num2;   
    		System.out.println("Sum="+sum); 
    	}
    	public static void main(String[] arg)
    	{
    		exfun4 ob=new exfun4();  
    		ob.add(5,9);   		
    	}
    }
                                        

    OUTPUT:
    
    E:\java\new_java>javac exfun4.java
    
    E:\java\new_java>java exfun4
    Sum=14
                                    

static keyword:

When a member is declared static, it can be accessed before any object of class is created, and without any reference to any object. We can declare both methods and variables to be static. The most common example of static member is main().

Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of static variable is made. Instead, all instances of the class share same static variable.

Static method can access only static data and it can call only other static methods. Static block can also be declared in order to initialize static variables. It gets executed only once, when the class is first loaded.

Example:
class exstatic
{
	static int a=3;    //Here, static variables are used as global variable
	static int b;
	int c;
	static void method1(int x)
	{
		System.out.println("x="+x);    //local variable can be used
		System.out.println("a="+a);
		System.out.println("b="+b);
		//System.out.println("c="+c);    //Error, c is an instance variable, therefore can't be used here
	}
	static
	{
		System.out.println("Inside static block");
		b=a*4;   //static variable b got initialized
	}
	public static void main(String[] arg)
	{
		method1(45);
	}
}
                            

OUTPUT:

E:\java\new_java>javac exstatic.java

E:\java\new_java>java exstatic
Inside static block
x=45
a=3
b=12
                        

Outside of the class in which static members are defined, static methods and variables can be used independently of any object. This is done by specifying the name of their class followed by the dot operator. i.e. classname.method()

Example:
class exst1
{
	static int a=42;
	static int b=49;
	static void callme()
	{
		System.out.println("a="+a);
	}
}

class exst2
{
	public static void main(String[] arg)
	{
		exst1.callme();
		System.out.println("b="+exst1.b);
	}	
}

                            

OUTPUT:

E:\java\new_java>javac exst2.java

E:\java\new_java>java exst2
a=42
b=49
                        

Nested and Inner Class:

When a class is defined within another class, such classes are known as nested classes. The scope of a nested class is bounded by the scope of its enclosing class.

There are two types of nested classes: static and non-static. A static nested class is one which has the static modifier applied. Because it is static, it must access the members of its enclosing class directly. Because of this restriction, static nested classes are seldom used.
The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same wat that other non-static members of the outer class do. Thus, an inner class is fully within the scope of its enclosing class.

The java compiler will give error message if any code outside of class outer attempts to instantiate class inner.

Example:
class outer
{
	int o_var=100;
	void test()
	{
		inner in=new inner();   
		in.display();  //Members of inner class can be accessed through its object, but not directly
		show_y();
	}
	class inner
	{
		int y=10;
		void display()
		{
			System.out.println("Outer variable="+o_var);   //Members of outer class can be used directly in inner class
		}
	}
	void show_y()
	{
		inner i1=new inner();
		System.out.println("y="+i1.y);
		//System.out.println("y="+y);   //y is a member of inner class, therefore, this statement gives error
	}
}

class exnested
{
	public static void main(String[] arg)
	{
		outer o=new outer();
		o.test();
		//inner i=new inner();   //inner class can't be instantiated outside its outer class
	}
}
                            

OUTPUT:

E:\java\new_java>javac exnested.java

E:\java\new_java>java exnested
Outer variable=100
y=10