Saturday, September 29, 2012

9/29/12 Instance variables in objects

In my last post, I explained what an object is in java. Objects use instance variables, which are variables that can only be accessed and changed using the object itself. If you want to find out what value an object has for a certain variable, you need to program the object to give you the variable. If you want to edit a variable, you need to program the object to change the value of that variable from an outside source. How do you do this, you may ask? Well, in this post I will teach you how to build a object such that you can let another class both  find the value of and edit its variables.

To do this, I will write out the code, and write // followed by an explanation of what it does.

public class object{

 private int a;
 private int b;
 //This creates 2 instance variables named a and b

 public object(){
  a = 0;
  b = 0;
 }
 //This defines the default value of a and b for a new instance    
 //of the class object

 public object(int newA,int newB){
  a = newA;
  b = newB;
 }
 //This defines the values of a and b for a new instance of the 
 //class object

 public void setA(int newA){
  a = newA;
 }
 //This will allow for you to change the value of a from outside 
 //the class object

 public void setB(int newB){
    b = newB;
 }
//This will allow for you to change the value of b from outside 
//the class object

 public int getA(){
  return a;
 }
 //This will return the value of a where it is needed outside of 
 //the class object


 public int getB(){
  return b;
 }
 //This will return the value of a where it is needed outside of 
 //the class object

 public String toString(){
  return a + " " + b;
 }
 //This will return a summery of all the variables in the class 
 //object to where it is called in another class

}


Hopefully you have learned a thing or two about objects, classes, and instance variables. If you have any questions, just post them on the comment section, and I will get back to you ASAP.

No comments:

Post a Comment