Friday, July 31, 2009

Encapsulation - Studying for my Programming exam and here is one of last years questions?

An object is said to have behaviour, state and identity. Discuss each of these and explain, using fragments of code, how each are exhibited in Java.





Part 2





Encapsulation is one of the fundamental concepts of object oriented programming. Explain what encapsulation is, using fragments of code, and discuss why it is important.





I would appreciate what you would consider to be a model answer or any help appreciated. Thank you very much!

Encapsulation - Studying for my Programming exam and here is one of last years questions?
In the Java virtual machine, an object's state is values of its instance variables. Its behavior is the actions it takes when you invoke its instance methods. Its identity is the address of the object image on the heap, which is available to programmers as its reference. If two object's have identical state and behavior, the way you can tell them apart is by comparing their references.





class Horsie {


String sound;


private boolean dogfood;


// a constructor


public Horsie() {


dogfood = false;


}


// an alternate (or Overloaded) constructor


public Horsie( boolean b ) {


dogfood = b;


}


// a method() for state


protected setDogfood( boolean b ) {


dogfood = b;


}


// a method for behavior


public void neigh() {


System.out.println("neigh");


}


}





That's a template of state, behavior.





class MainApp {





public static main(String[] args) {





Horsie trigger = new Horsie();


// that's identity


Horsie silver = new Horsie( true );





the keyword "new" uses the template and puts the Object on the computer heap (into the computer)





if( trigger.equals(silver) )


No, the 2 Objects are not equal. They reside at different addresses in computer





if( silver typeof Horsie )


silver.neigh();





The rest you can BS...





===========





Encapsulation groups variables. If ...





class myClass {


// everything between { and }


// can only belong to myClass


}


// ...if this were not so, the human would have to contrive 100,000 variables and the human would have to remember the contents of those 100,000 variables.





Both Object traits and Encapsulation allow one "floorplan" or "blueprint" that allows multiple computer items, like an animated clock to appear in multiple locations on the computer screen, each with it's own sense of time.





The rest you can WOW them with in BS terms.
Reply:Encapsulation is more fundamental that the previous respondents answer. Encapsulation is where the data used by an object are only access via published methods. The purpose being the object retains control of the value and its state is only changed by the object.


No comments:

Post a Comment