Flat Preloader Icon

Static Members & Method Overloading

Static Members

  • Static members are class level members.
  • Creating Object
  • These do not need an already existing object to be used.
  • Used to distinguish class level variables from local vari

Method Overloading

  • Same method names in a class having different arguments.
  • Useful in cases where the functionality desired is similar
  • E.g. public double calculateTriangleArea(int base, int height); & public double calculateTriangleArea(int a, int b,int c);

Static Members

Static members in Java are class-level members that are associated with the class itself rather than with any specific instance of the class (object). They are declared using the static keyword. There are two types of static members:

Static Variables (Class Variables)

  • Static variables are shared among all instances of a class.
  • They are initialized only once, typically when the class is loaded.
  • You can access them using the class name or an instance of the class.
  • Example:
				
					public class MyClass {
    static int count = 0; // Static variable

    public MyClass() {
        count++; 
// Increment count each
time a new instance is created
    }
}
				
			

Static Methods

  • Static methods are associated with the class itself and not with any specific instance.
  • They can be called using the class name, and they cannot access instance-specific (non-static) members directly.
  • They are often used for utility functions or operations that don’t depend on instance-specific data.
  • Example:
  • 				
    					public class MathUtils {
        public static int add(int a, int b) {
            return a + b;
        }
    }
    
    				
    			

    Method Overloading

    • Same method names in a class having different arguments.
    • Useful in cases where the functionality desired is similar
    • E.g. public double calculateTriangleArea(int base, int height); & public double calculateTriangleArea(int a, int b,int c);
    Key points about method overloading:

    The return type of the method is not considered when overloading methods. Two overloaded methods can have the same name and parameter types but different