Sunday, October 21, 2012

Use "getter" and "setter" method in JAVA !!!



In this method, we put instance variable private and getter and setter public. Below is the simple program which explain this method.  

First we create a class named "animal" which declare the setter and getter method.





public class Animal {

 private int numOfSpeicies;
 private String name;



  public int getNumofSpeicies(){  // getter method

  return numOfSpeicies;
 }

 public String getName(){         // getter method
  
  return name;
 }



  public void setNumofspecies(int n){   // setter method
  
 numOfSpeicies = n;

 }

 public void setName(String n){          // setter method
  
 name = n;

       }

}




In above program, we declare instance variable "numofspeicies" and "name" private and make getter and setter public.


__________________________________________________________



Now create another class named "animaltest" and lets see what happen next..........................



public class Animaltest {

  public static void main(String[] args) {
  
  Animal reptile = new Animal();
  
    
  reptile.setName("Crocodile, Snake, Turtle, Lizard, Tuataras");
  reptile.setNumofspecies(5);
  
  
  
  System.out.println("Animal type is: " + reptile.getName() );
  
  System.out.println("No of Animal is:" +reptile.getNumofSpeicies());
  
  
 }

}

___________________________________________________________________
Output:



Animal type is: Crocodile, Snake, Turtle, Lizard, Tuataras
No of Animal is: 5

____________________________________________________________________

In above program we create an object called "reptile". With help of setter method we write down all reptiles name and number of reptiles. And with getter method we call it in System.out.println("    "); so that we can get the same value which we put in setter method.

You can copy and paste this code but if you start write this code manually than, it really help you to remember this methods. Try it on your own than tell me the difference !

Thank you for viewing this post.........

No comments:

Post a Comment