Difference between Static methods and Instance methods

前端 未结 10 1318
青春惊慌失措
青春惊慌失措 2020-11-22 05:30

I was just reading over the text given to me in my textbook and I\'m not really sure I understand what it is saying. It\'s basically telling me that static methods or class

10条回答
  •  长发绾君心
    2020-11-22 05:51

    In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.

    This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.

    class A {
        int a;
        int b;
    
        public void setParameters(int a, int b){
            this.a = a;
            this.b = b;
        }
        public int add(){
            return this.a + this.b;
       }
    
        public static returnSum(int s1, int s2){
            return (s1 + s2);
        }
    }
    

    In the above example, when you call add() as:

    A objA = new A();
    objA.setParameters(1,2); //since it is instance method, call it using object
    objA.add(); // returns 3 
    
    B objB = new B();
    objB.setParameters(3,2);
    objB.add(); // returns 5
    
    //calling static method
    // since it is a class level method, you can call it using class itself
    A.returnSum(4,6); //returns 10
    
    class B{
        int s=8;
        int t = 8;
        public addition(int s,int t){
           A.returnSum(s,t);//returns 16
        }
    }
    

    In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.

提交回复
热议问题