KKK
KKK

Reputation: 1662

Where can i use class methods and instance methods in java

Where can I use an instance method and where is it appropriate to use a class method?

I know the term of class and instance method.

Upvotes: 0

Views: 3435

Answers (8)

siddhant mathur
siddhant mathur

Reputation: 1

i am giving a brief explanation since i myself am learning about java,but what i have understood in simple language is-

instance methods-dynamic,work with whole objective or purpose of the object in question class instances-are static,deal with a particular topic concerned with all the objects

Upvotes: 0

Costis Aivalis
Costis Aivalis

Reputation: 13728

Ivor Horton has a great example in his book, with a Sphere class. He defines getCount() as a class method, because it gives you the ability to count the number of Spheres you have created, even when there is no Sphere object it returns 0. volume() on the other hand, is an instance method since it calculates the volume of a specific sphere and you have a different volume for every Sphere instance.

public class Sphere {
   static final double PI = 3.14; // Class variable that has a fixed value
   static int count = 0; // Class variable to count objects
   // Instance variables
   double radius; // Radius of a sphere
   double xCenter; // 3D coordinates
   double yCenter; // of the center
   double zCenter; // of a sphere

   // Class constructor
   public Sphere(double theRadius, double x, double y, double z) {
      radius = theRadius; // Set the radius
      // Set the coordinates of the center
      xCenter = x;
      yCenter = y;
      zCenter = z;
      ++count; // Update object count
   }

   // Static method to report the number of objects created
   public static int getCount() {
      return count; // Return current object count
   }

   // Instance method to calculate volume
   public double volume() {
      return 4.0/3.0*PI*radius*radius*radius;
   }
}

Try it out with this class:

public class CreateSpheres {
   public static void main(String[] args) {
      System.out.println(“Number of objects = “ + Sphere.getCount());
      Sphere ball = new Sphere(4.0, 0.0, 0.0, 0.0); // Create a sphere
      System.out.println(“Number of objects = “ + ball.getCount());
      Sphere globe = new Sphere(12.0, 1.0, 1.0, 1.0); // Create a sphere
      System.out.println(“Number of objects = “ + Sphere.getCount());
      // Output the volume of each sphere
      System.out.println(“ball volume = “ + ball.volume());
      System.out.println(“globe volume = “ + globe.volume());
   }
}

Upvotes: 1

Romski
Romski

Reputation: 1942

This is about understanding representations and their uses.

If you have a class that represents a person, all people may share the same attributes, but their specific attributes will differ. So everyone has a height, but some people are shorter and others taller. To represent a person you need a specific instance that says "my name is bob and im 2m tall", or "my name is sally im 1.9m tall". Your representation of a person depends on the specific instance.

However some things can be represented universally. For example, adding one number to another will always yield the same result, so there's no need for many representations. Hence the Math class has static methods.

In practice, with Java, the jvm will load a class and use it as a "blueprint" for creating instances (all people will share the same attributes, even if their actual values vary), or as the universal definition (for statically declared stuff). For static methods you should be wary of synchronisation (it helps to understand the heap/stack), as well as potential bottlenecks. In distributed applications, the universal definition may be loaded more than once (per jvm).

Upvotes: 1

Sap
Sap

Reputation: 5321

Static methods are class level methods, they are good for utility methods for example Math class in Java. These classes usually take a few inputs work with them and gives desired output(For example Math.pow(4,5)).

Instance methods rather work with the whole object in question. Good example would be almost any class of Java. Still, for example; FileInputStream where read() method reads data from underlying stream.

Example of static method would be

class Math(){
public static long multiply(long a, long b){
   return a*b;
}
public static void main(String[]args){
  System.out.println(Math.multiply());
}
}

Example of instance method can be

class User(){
private String pass;
private String uname;

    public User(String p,String u){
      pass=p;
      uname=u;
    }
    public boolean authenticate(){
      if("secret".equals(this.pass) && "Grrrr".equals(this.uname){
         return true;
      }else{
         return false;
      }
    }
    public static void main(String[]args){
     User u = new User("wrong secret","grrr");
     System.out.println(u.authenticate());
    }
  }

In the second example pay attention to the fact that to use the instance method we must create an object first and then only call the method.

Upvotes: 5

Maciej Miklas
Maciej Miklas

Reputation: 3330

Static methods are suitable for utility classes and to create singletons. Basically in 90% you will avoid static methods.

You cannot overwrite static method using inheritance (polymorphism) - you can only shadow it. Shadowing is anti paten in OOD.

Static methods should not be part of Object Oriented Design - use them only as technical helpers.

Upvotes: 1

Gruber
Gruber

Reputation: 551

Hoi,

i can add the following reference:

Excerpt of Joshua Bloch's "Effective Java"

or as Print:

Effective Java (2nd Edition) [Paperback]

The book is really great and anyone wanting to write better code should at least skim it ^^

cu

Upvotes: 2

Rakesh
Rakesh

Reputation: 4334

Static methods are conceptually the same as static variables, thus the reasons to use or not use them are similar. They belong to the class, not specific objects of that class. An example from the java API is Math, all the variables are static. Does it make sense to have to create a Math object just to call a single method? Other then the fact that the methods perform some mathematical operation, there is little relation between them. In other words, there are no logical instance variables that would tie the math methods together. As an aside, you can't instantiate Math, so don't waste time trying.

A simple answer to why and when is 'whenever it makes sense". If a method needs to be in a class, but not tied to an object, then it makes sense. If the method is more logically part of an object, then it shouldn't be

Main is static because someone at Sun decided it would be better if the JVM could call main without creating an object first. It probably simplified the design of the JVM.

Upvotes: 3

nwinkler
nwinkler

Reputation: 54507

Here's the link to the Java tutorial, which has a good overview, with examples and code:

Upvotes: 1

Related Questions