Java & J2EE Java Classes |
We touched on Classes and Objects in my article on Java and Object-Oriented Programming, which you can find here: http://www.devshed.com/c/a/Java/Java-and-ObjectOriented-Programming/2/ Objects and Classes: What Are They? An object is made up of states and behaviors and is usually used as a model for objects in the real world. An example of an object might be a Ford truck. Classes, meanwhile, would represent the category of Trucks. There can be Ford Trucks, Chevy Trucks, Dodge Trucks, and so forth, and while they may vary from one another in certain ways, fundamentally they are all part of the truck class, and therefore all share the same basic truck foundations (i.e.; four tires, a flatbed, etc). Here is an example of a class declaration: public class BruceLee { //We will give Bruce Lee three fields public int punch; public int kick; public int roundhouse; //We will provide one constructor for Bruce public BruceLee(int usePunch, int useKick, int useRoundhouse) { punch=usePunch; kick=useKick; roundhouse=useRoundhouse; } //We will give Bruce Lee three methods public void setPunch (int someNewValue) { punch = someNewValue; } public void setKick (int someNewValue) { kick = someNewValue; } public void setRoundhouse (int someNewValue) { roundhouse = someNewValue; } } Now if we said that the class BruceLee had pupils, or subclasses, we could declare that subclass like so: public class Pupil extends BruceLee { // We give Pupil one field public int eyePoke; //And one Constructor public Pupil(int usePunch, int useKick, int useRoundhouse) { flex(usePunch, useKick, useRoundhouse); eyepoke=usePunch; } //And one method public void finger(int someNewValue) { eyepoke=somenewValue; } } Don't worry if that doesn't makes sense right now; it doesn't even make sense to me and I wrote it. But I promise you by the end of this tutorial it will appear brilliant. In the above example, Pupil inherits all of the fields of BruceLee, since it is a subclass of his, and adds its own field (eyepoke) and a method to use it (finger).
blog comments powered by Disqus |
|
|
|
|
|
|
|