Advertisement
Guest User

Untitled

a guest
May 22nd, 2015
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.30 KB | None | 0 0
  1. class Frog //Frog class, frog used as no better word could be thought of, nothing of significance.
  2. {
  3.     private String name; //private objects can only be accessed from within the same class.
  4.     private int age; //This is forcing encapsulation so that a classes properties can only be modified using the class (well... its methods).
  5.    
  6.     public void setName(String newName) //Creating a set method to change the name of the frog instance.
  7.     {
  8.         name = newName;
  9.     }
  10.    
  11.     public void setAge(int newAge) //Creating a set method to change the age of the frog instance.
  12.     {
  13.         age = newAge;
  14.     }
  15.    
  16.     public String getName() //Creating a get method to return the name of the frog instance.
  17.     {
  18.         return name;
  19.     }
  20.    
  21.     public int getAge() //Creating a get method to return the age of the frog instance.
  22.     {
  23.         return age;
  24.     }
  25. }
  26.  
  27. public class Application
  28. {
  29.     public static void main(String[] args)
  30.     {
  31.         Frog frog1 = new Frog();
  32.        
  33.         //frog1.name = "Bertie"; //This code will not work because the variables are set to private meaning they are not accessible from this place in the code.
  34.         //frog1.age = 1; //Same case with this line.
  35.        
  36.         frog1.setName("Bertie"); //This is the same as the code on line 27. Except this calls a method to change the property.
  37.         frog1.setAge(1);
  38.  
  39.         System.out.println(frog1.getName());
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement