Java Method

  1. Syntax
  2. Method Creation in Java
  3. Method Overloading in Java
  4. Method Overriding 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


Method

class ClassName {
 
	returnType functionName(Arguments) {
 
		// Statements..
	}
}
 
class MainClass {
 
	public static void main(String args[]) {
 
		ClassName objName = new ClassName();
		objName.functionName(Arguments);
	}
}





B. Method Creation in Java


Method_Ex1.java

public class Method_Ex1 {
	
	int x, y;
	float z;
	
	Method_Ex1() {
		
		x = 20;
		y = 10;
	}
	
	void add() {
		
		z = x + y;
		display(z);
	}
	
	void sub() {
		
		z = x - y;
		display(z);
	}
	
	void multi() {
		
		z = x * y;
		display(z);
	}
	
	void div() {
		
		z = x / y;
		display(z);
	}
 
	private void display(float ans) {
		// TODO Auto-generated method stub
		
		System.out.println(ans);
	}
}
 
class MainClass {
	
	public static void main(String args[]) {
		
		Method_Ex1 obj = new Method_Ex1();
		
		obj.add();
		obj.sub();
		obj.multi();
		obj.div();
	}
}

Sample Output

30.0
10.0
200.0
2.0




C. Method Overloading in Java


Method_Ex2.java

public class Method_Ex2 {
	
	void display() {
		
		System.out.println("Method Overloading..");
	}
	
	void display(int x) {
		
		System.out.println("Int Value : " + x);
	}
	
	void display(float x) {
		
		System.out.println("Float Value : " + x);
	}
	
	void display(char x) {
		
		System.out.println("Char Value : " + x);
	}
	
	void display(int x, int y) {
		
		System.out.println("Int, Int : " + x + ", "+ y);
	}
	
	void display(int x, float y) {
		
		System.out.println("Int, Float : " + x + ", "+ y);
	}
	
	void display(float x, int y) {
		
		System.out.println("Float, Int : " + x + ", "+ y);
	}
}
 
class MainClass {
	
	public static void main(String args[]) {
		
		Method_Ex2 obj = new Method_Ex2();
		
		obj.display();
		obj.display(111);
		obj.display((float) 48.57);
		obj.display('B');
		obj.display(11, 20);
		obj.display(530, (float) 131.33);
		obj.display((float) 123.24, 52);
	}
}

Sample Output

Method Overloading..
Int Value : 111
Float Value : 48.57
Char Value : B
Int, Int : 11, 20
Int, Float : 530, 131.33
Float, Int : 123.24, 52




D. Method Overriding in Java


Method_Ex3.java

public class Method_Ex3 {
	
	void display() {
		
		System.out.println("Class : Method_Ex3");
	}
}
 
class SubClass1 extends Method_Ex3 {
	
	void display() {
		
		super.display();
		
		System.out.println("Class : SubClass1");
	}
}
 
class MainClass {
	
	public static void main(String args[]) {
		
		SubClass1 obj = new SubClass1();
		obj.display();
	}
}

Sample Output

Class : Method_Ex3
Class : SubClass1






SHARE THIS PAGE



product 2

product 3

Feedbacks : balaji.scz@gmail.com