In this post, we’ll learn static and instance method in java programming.
/**
* Author : DarkL0rd
* Created : 9 Jan 2023 Monday
* Define : Static n Instance Methods
*/
public class StaticDemo {
//Instance Variable
String instanceMessage = "Instance Variable";
//int count;
//Static Variable
static String messages = "Static Variable";
public static void main(String[] args) {
// Invoke Static to instance variable cant
//System.out.println(instanceMessage);
// Invoke Static Variable is OK
System.out.println(messages);
//Can invoke to static method from here
//hello();
// Greet is not static method
// Instance Method can't invoke from Static
//greet();
//Created Objected first and Invoke to InstanceMethod
StaticDemo demo = new StaticDemo();
demo.instanceMethod();
}
//Instance Method
//Instance method's owner is an Object. Not class.
void instanceMethod() {
System.out.println("Instance Method");
//Instance Variable
System.out.println(instanceMessage);
//Static Variable
System.out.println(messages);
//StaticMethod
hello();
//InstanceMethod
greet();
}
//Static Method
static void hello() {
System.out.println("Hello Static Method");
}
//Instance Method
void greet() {
System.out.println("Hello Java");
}
}
Variable Arguments in Java.
public class Varargs {
//Static Method
//Only can invoke from included class type
public static void main(String[] args) {
// Array
String [] array = {"A", "B"};
// Invoking Method
show("Hello",array);
}
static void show(String ... strs) {
for (String str : strs) {
System.out.println(str);
}
}
static void show(String string, String ... strs) {
System.out.println("First " + string);
for (String str : strs) {
System.out.println(str);
}
}
// Instance Method
void greet() {
System.out.println();
}
}
Method’s Loading Time for testing.
import java.util.Scanner;
public class LoadingTime {
public static void main(String[] args) {
System.out.println("Start Program");
//Create an obj
//Scanner obj is waiting to program
Scanner sc = new Scanner(System.in);
sc.nextLine();
LoadDemo demo;
System.out.println("Declared Class");
sc.nextLine();
demo = new LoadDemo();
System.out.println("Created Object from Class");
sc.nextLine();
demo = new LoadDemo();
System.out.println("Created Object again");
sc.nextLine();
}
}
class LoadDemo {
//Static Block
//After class declaration, static works
//Only one time work
static {
System.out.println("Static Block");
}
//Instance Block
//After static works
{
System.out.println("Instance Block");
}
//Constructor
//After instance works
LoadDemo() {
System.out.println("Constructor");
}
}
Better than Others, Harder than Ever.
Thanks for your time.