Java Classes

Well it’s been a while since we discussed Java and I graced these pages with its complicated beauty (for an example of complicated beauty, take a peek at Hillary Swank, who is pretty in a well…complicated sort of way). In this new series of articles, we will be discussing 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).

{mospagebreak title=How to Declare a Class}

There are several ways to define your classes. The simplest would be:


class YourClass {

declare your field, constructor, and methods here

}

You can also define them in a more complex manner: 

class YourClass extends YourSuperClass implements SomeInterface {

declare your field, constructor, and methods here

}


Here is a list of components class declarations can contain:

  • Public, Private, and other modifiers.

  • Class Name.

  • Superclass name, if applicable with the keyword extends before it.

  • The keyword implements followed by a list of interfaces (separated by commas).

  • Body of the class, encapsulated with braces{}.

Variables in Classes

We discussed variables and data types in a previous article, but they need a little further discussion here, as they relate to classes.

Variables in classes are known as member variables and are called fields. They are composed of a modifier (such as public or private), a type, and a name. An example would be:


public int myEnormousIQ;


In the above example, the public portion of our declaration is known as an access modifier. It determines which classes have access to the member field. There are several access modifiers: public, protected, package, and private.

  • Public: can be referenced from anywhere in the application by the class in which it is defined.

  • Package: can be referenced by only the same package through the class in which it was defined.

  • Private: can only be referenced by the class in which it was defined.

  • Protected: can be referenced by its class and subclass and from its package.

{mospagebreak title=Using Public Methods to Obtain Private Fields}

It is common practice to make member fields private. However, sometimes we still need access to the data they contain throughout our program. To retrieve this data, we can use methods, like so:


public class BruceLee {

private int punch;

private int kick;

private int roundhouse;

public BruceLee(int doPunch, int doKick, int doRoundhouse) {

punch = doPunch;

kick = doKick;

roundhouse = doRoundhouse;

}

public int gimmePunch() {

return punch;

}

 

public void determinePunch(int newPunch)) {

punch = newPunch;

}

}

public int gimmekick() {

return kick;

}

public void determineKick(int newKick)) {

kick = newKick;

}

}

public int gimmeRoundhouse() {

return roundhouse;

}

public void determineRoundhouse(int newRoundHouse)) {

roundhouse = newRoundHouse;

}

}

Declaring Methods

A method declaration looks like this:


public double decideWhoIsFatter(double yourWeight, int myWeight) {

insert math here

}

The required parts of a method declaration are the return type, name, some parentheses(), and a body located between two braces{}. There are six possible parts of a method declaration:

  • Modifier: public, private, protected, and package

  • Return type: the returned value’s data type, or void if there is no value returned by the method

  • Method name: name of the method

  • Parameter: a list of input parameters, separated by commas, and preceded by data types. They are always enclosed in parentheses, unless there are no parameters, in which case you use two parentheses with nothing in between. 

  • Exception Lists: discussed in a future issue

  • Method Body: the code of the method enclosed between braces.

{mospagebreak title=Naming Conventions for Our Pal, the Method}

Methods can be named the same as classes. However, a bunch of nerds decided that they should all use the same convention, and that method names should be a lowercase verb, or if you want to add more than one word, then the second, third, and so forth words should have their first letter capitalized.

Here are some examples of good method naming conventions:

  retrieveInfo

  killBoss

  eatChickenMcnuggets

  sleepAtWorkAndStillGetPaid

  dateAngelinaJolie

  watchMidgetWrestling

  slapMisterTThenRunLikeHell

Most of the time methods will have a unique name. However, Java does allow for a little thing called overloading, which allows different methods to be named the same and yet still be distinguishable from one another due to method signatures. A method signature consists of its name and parameter types. An example of two methods with the same name and different signatures would be:


killChuckNorris(int, int, int, double)

killChuckNorris(double, double, double, int)


Overloading is a little beyond the scope of this article, however we will discuss it in the future.

Constructors: More than Meets the Eye

Constructors can be thought of as big beluga construction workers, sitting on a fence and swinging their feet back and forth as they eat from a solid metal sandwich pail, cat-calling and generally going nuts when dames and broads with gams up to here walk by.

Aside from belittling women and eating big sammiches, constructors also build objects based on blueprints that you provide. Who’da thunk you’d grow up to be a fancy-schmancy architect type?

There are three types of constructors (unless you include copy, which we won’t): default, non-default, and cloning. I’ll describe each one briefly below:

The Good Default Constructor

Default constructors are typically used to create the most basic instance possible, which means giving all the members a value such as null or zero, or even an empty string. You can assign values, mind you, but typically you don’t or some nerd will yell at you for being a bad programmer.

The Bad Non-Default Constructor

A non-default constructor is used to create an object with most of its values defined for all of the object’s members. If your mother was an object, we could say that she is ugly, she is fat, she is easy, she loves the navy, and she votes Democratic.

The Ugly Clone Constructor

Settle down all you Star Wars nerds. I know the mere mention of the word Clone stirs you into a Clone Bores frenzy. Clone does what it probably sounds like: replicates an object.

{mospagebreak title=Creating Objects with Constructors}

Classes contain constructors, which are used to create objects based off of that class’ blueprints. The declaration of a constructor is similar to that of a method, with the exception that they use the same name as the class and have no return type. Here is an example of the BruceLee constructor: 

public BruceLee(int doKick, int doPunch, int doRoundhouse) {

punch = doPunch;

kick = doKick;

roundhouse = doRoundhouse;

}

If we wanted to create a new BruceLee object and name it myPupil, we could use the new operator to do so:

BruceLee myPupil = new BruceLee(10, 5, 2);

Now a new object name myPupil has been created, and its punch, kick, and roundhouse have all been assigned the values 10, 5, and 2, respectively.

Well that’s all the time we have for this article. In our next part, we will learn to pass information to a Method or constructor, and work more with Objects.

Till then…

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort