Wednesday, June 3, 2015
Static Methods
// When we define a STATIC METHOD, the method is still a member of a class,
// since you can define it in a class, but the method can be invoked without using any object.
// ClassName.methodName
// You can create a collection of static methods to perform computation that are
// somehow related and group them within a single class
// A NON-STATIC method van reference a static variable or static methods
// A STATIC method can reference a static variable but not an instance variable directly
// A STATIC method cannot call a NON_STATIC variable/method without having an
// instance of a class to use in the invocation.
// Cannot use "this" or "super" keyword in the STATIC methods
// Why main method is static?
// Main method is static because if we do not declare static different class objects will make
// different main method due to which bugs occur so, if we declare main as static it will be the
// common method or action for different classes object
// When a method performs a task that is independent of the contents of the object, make it static.
// None of the methods in the Math class such as random(), pow(), sin() is dependent
// on specific instance. So these methods are static methods
public class StaticMethodsDemo
{
public static void main(String[] args)
{
Demo.staticString = "changedStaticBpn";
Demo.staticMethod();
Demo d = new Demo();
d.normalString = "changedNormalBpn";
d.normalMethod();
}
}
class Demo
{
String normalString = "NormalBipen" ;
static String staticString = "staticBipen" ;
public void normalMethod()
{
System.out.println("\n------NormalMethod------");
System.out.println(normalString);
System.out.println(staticString);
staticMethod();
}
public static void staticMethod()
{
System.out.println("\n---------StaticMethod--------");
System.out.println(staticString);
// System.out.println(normalString);
// normalMethod();
// this above two case is not possible but can be posible by creating object
//----------Now by making an object---------
Demo de = new Demo();
// System.out.println(de.normalString);
// System.out.println();
}
}
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment