Java Class

  1. Syntax for a Class in Java
  2. Create a Class in Java
  3. Create More Classes in Java
  4. Create Nested Classes in Java

Note
Here I am using,
OS : Linux (Ubuntu 12.04)
IDE : Eclipse Tool
Eclipse : Juno (Version 4.2.0)
Package : Default package

A. Syntax for a Class in Java


ClassName.java

public class ClassName {
 
	// Declare Variables and Method
	
	public ClassName() {
		
		// Initialise values to Variables		
	}
	
	public void functionName() {
		
		// Write Code Inside Method		
	}
}
 
class MainClassName {
	
	public static void main(String args[]) {
		
		/* 
		 * 
		 * Create Object to ClassName class 
		 * 
		 * Access Variables and Methods inside ClassName class
		 * 
		 */		
	}
}




B. Create a Class in Java


Class_Example_1.java

public class Class_Example_1 {
 
	int a;
	float b;
	String str;
	
	public Class_Example_1()
	{
		a = 10;
		b = (float) 15.26;
		str = "Java";
	}
	
	public void display()
	{
		System.out.println("The Integer Value is : "+a);
		System.out.println("The Float Value is : "+b);
		System.out.println("The String Value is : "+str);
	}
}
 
class mainClass {
	
	public static void main (String args[])
	{
		Class_Example_1 obj = new Class_Example_1();
		
		obj.display();
	}
}

Sample Output

The Integer Value is : 10
The Float Value is : 15.26
The String Value is : Java




C. Create More Classes in Java


Class_Example_2.java

public class Class_Example_2 {
	
	void display1() {
		
		System.out.println("This is Class - 1");
	}
}
 
class Class2 {
	
	void display2() {
		
		System.out.println("This is Class - 2");
	}
}
 
class Class3 {
	
	void display3() {
		
		System.out.println("This is Class - 3");
	}
}
 
class MainClass {
	
	public static void main(String[] args) {
		
		Class_Example_2 obj1 = new Class_Example_2();
		Class2 obj2 = new Class2();
		Class3 obj3 = new Class3();
		
		obj1.display1();
		obj2.display2();
		obj3.display3();
	}
}

Sample Output

This is Class - 1
This is Class - 2
This is Class - 3




D. Create Nested Classes in Java


Class_Ex4.java

public class Class_Ex4 {
	
	int a, b, c;
	
	Class_Ex4() {
		
		a = 10;
		b = 20;
	}
	
	class InnerClass {
		
		InnerClass() {
			
			c = a +b;
		}
		
		void display() {
			
			System.out.println("The Addition is : " + c);
		}
	}
	
	void display() {
		
		System.out.println("'A' is : " + a);
		System.out.println("'B' is : " + b);
	}
}
 
class MainClass {
	
	public static void main(String args[]) {
		
		Class_Ex4 obj1 = new Class_Ex4();
		Class_Ex4.InnerClass obj2 = obj1.new InnerClass();

		obj1.display();
		obj2.display();
	}
}

Sample Output

'A' is : 10
'B' is : 20
The Addition is : 30






SHARE THIS PAGE



product 2

product 3

Feedbacks : balaji.scz@gmail.com