Вы находитесь на странице: 1из 11

Classes and Objects

In object-oriented programming methodology an OBJECT is a software bundle of related properties and behaviors that are often used to model the real-world objects that you find in everyday life while a CLASS is a blueprint or prototype from which all OBJECTS are created. [The Java Tutorial] Essentially, an object is an instance of a class. In a real-world perspective, a HUMAN is an example of a CLASS. As a blueprint, the genetic make-up of a human dictates that a human must have human body parts (like head, arms, legs, etc) and must be capable of exhibiting human emotions (like joy, anger, etc) In this regard, MR. BENIGNO SIMEON AQUINO III is an instance of the class named HUMAN. If Mr. Aquino is human therefore he must have body parts and exhibit emotions. As it happens, MS. GLORIA MACAPAGAL ARROYO [as well as the entire population of humans who ever walked on the face of the earth] are also instances of the HUMAN class. That means they all have body parts and exhibit emotions without any exceptions whatsoever. Furthermore, if Mr. Aquino and Mrs. Arroyo are both humans it means that they both have the same set of body parts and are capable of exhibiting the same set of emotions. But this does not mean that these two political figures are the same! One obvious example is that both Mr. Aquino and Mrs. Arroyo have a GENDER. But why are they not the same? Because the GENDER of the former is male and the latter is female. They possess the same PROPERTY but the STATE of the property is different, therefore they are different humans. Another example is that both are capable of exhibiting ANGER. But why are they not the same? Because these two persons get ANGRY for different reasons, in different ways and at different times. They possess the same BEHAVIOR but the METHOD used to express this behavior is different, therefore they are different humans Thus, two observations can be made about objects and classes: One CLASS can have several OBJECTS that are instances of that class sharing the same properties and behaviors. Even if different OBJECTS of the same CLASS all have the same property and behavior, they are still different because the current state of their property and the method that is used to express their behavior may be different. In JAVA, the property and behavior are implemented as the property/attribute and methods of an OBJECT which are created by defining CLASSES.

CREATING A CLASS
In Java, all programs are treated as classes. To create a class, one simple creates a .java file whose filename must be the same as the name of the class that will be created. Thus, if one wishes to create a Fraction class, a file named Fraction.java must be created and, inside, a public class named Fraction should be declared.
Fraction.java publ i c class Fraction { // class definition placed here ... }

PARTS OF A CLASS
All Java classes must define three components: PROPERTIES, CONSTRUCTORS and METHODS. Properties define the set of data that will be kept in the class. Constructors provide the client programs some means to instantiate objects of that class they are used to initialize the properties of the class. Methods provide the operations that allow the client programs to further manipulate the properties of the class. By convention, the name of properties and methods start with a lowercase letter while classes and constructors start with an uppercase letter. Furthermore, properties and classes should be named after nouns+adjectives while methods should be named after verbs+adverbs. Example:
Fraction.java publ i c class Fraction { // PROPERTIES: int numerator ; int denominator ; define the set of data that comprises an instance of the class

// CONSTRUCTORS: defines how the PROPERTIES of the class are initialized every // time Fractions are instantiated public Fraction() { thi s numerator = 0; . thi s denominator = 1; . } // METHODS: defines how the PROPERTIES of the class can be manipulated public void incrementBy ( in t numerator , int denominator) { thi s numerator . = s thi .numerator*denominator + this.denominator*numerator; this.denominator = this.denominator*denominator; } public double toFloatingPoint() { return (double)numerator/denominator; } } //
end of class Fract i on

So that given the class definition of Fraction, a client program can use that class as follows:
Client. java publ i c class Client { public static void main(String[] args) { Fraction sample; double real; sample = new Fraction(); sample.numerator = 3; sample.denominator = 5; sample.incrementBy (1, 2); real = sample.toFloatingPoint(); } // } //
end of the ( ) method main

end of the Client class

USING THE CLASS


Observing the code in Client.java, the following can be observed about the Fraction class 1. Once the class has been created it can now be used as the data type of variables in the client program Example: Fraction myFract ion / / a fract i on ;
Fraction[] myList; // an array of fractions Fraction[][] myTable; // a two-dimensional array of fractions fraction anotherFraction; // wrong! Fraction is not spelled Fractions yetAnotherFraction; // correctly

2. Of the three components of a class, the constructors are independent they exist even if no variables of that class have ever been created and they are always the first to be used to instantiate objects of that class. Example:
Fraction myFraction; Fraction[] myList; Fraction[][] myTable; String myString; int myInteger; myFraction = new Fraction(); myList = new Fraction[3]; myList[0] = new Fraction(); myList[1] = new Fraction(); myList[2] = new Fraction(); myTable = new Fraction[2][2]; myTable[0][0] = new Fraction(); myTable[0][1] = new Fraction(); myTable[1][0] = new Fraction(); myTable[1][1] = new Fraction(); myString = new Fraction(); myInteger = new Fraction(); // instantiates a Fraction // instantiates 3 Fractions // for each of the 3 array elements // a Fraction // an array of Fractions // a two-dimensional array of Fractions

// instantiates 4 Fractions // for each of the 4 array elements

// wrong! myString is not a Fraction // wrong! myInteger is not a Fraction

3. Unlike constructors, the properties and the methods only exist if objects of that class have been instantiated such that the properties and methods represent the state and behavior of the object where they belong to. Collectively, they are referred to as members of the class and they are referenced [from the variable of that class] using the member-of operator represented by (a dot). Example:
/** * Class Fraction * Properties: * - int numerator * - int denominator */ Methods: - void increaseBy (int,int) - double toFloatingPoint() // a Fraction

Fraction myFraction; String myString; int myInteger;

myFraction.numerator = 3; // wrong! myFraction is not yet myFraction.denominator = 5; // instantiated, therefore numerator and // denominator does not yet exist myFraction = new Fraction(); myFraction.numerator = 3; myFraction.denominator = 5;
// correc t ! / / correc t !

myFract ion .num = 3; myFraction.den = 5; myFraction.denominator() = 5; denominator = 5;

/ / wrong! num property does not exist // wrong! den property does not exist // wrong! denominator is not a method // wrong! must be referenced only from // myFraction
// correc t !

myFraction.increaseBy(1,2); / / correc t ! System.out .pr i n t( n l myFraction.toFloatingPoint() ); myFraction.increaseBy ; myFraction.increaseBy(); myFraction.increaseBy(1,2); myFraction,increaseBy(1,2); myFraction.increase(1,2); myString.numerator = 3; myInteger.numerator = 3;

// wrong! increaseBy is not a property // wrong! two arguments must be provided // wrong! arguments must be integers // wrong! member-of operator must be used // wrong! increase() method does not exist // wrong! myString is not a Fraction // wrong! myInteger is not a Fraction

CONSTRUCTORS AND METHODS


In defining constructors and methods in a Java class, the following has to be observed. A pair of open-close parentheses is attached at the end of the name of constructors and method, e.g. Fract i on), incrementBy . . , toFloatingPoint() ( (. ) as compared to properties where parenthesis are not used, e.g. numerator, denominator Constructors do not have any return type and must be named after the class where they are being defined, for example:
publ i c class Fraction { publ i c Fraction() { ... } // correct!

publ i c Fraction { // wrong! must have a pair of parenthesis ... // attached to the constructors name } publ i c Friction() { ... } // wrong! must have same name as the class

publ i c int Fraction() { // wrong! must not have any return type ... }
// end of the Fract i on class

Methods must have a return type and can be given any name except the name of the class where it is being defined, for example:
publ i c class Fraction { publ i c void incrementBy (int numerator, int denominator) { // correct! ... } publ i c int toFloatingPoint() { ... } publ i c void Fraction() { ... // correct!

// wrong! must not have the same name // as the class

} publ i c getReciprocal() { ... } publ i c Fract ion getReciprocal { ... } publ i c Fraction getReciprocal() { ... } }
// end of the Fract i on Class

/ / wrong! must have a return type

/ / wrong! must have a pair of / / parenthesis attached to the / / methods name / / correct !

The pair of open-close parentheses attached after the name of a constructor or a method defines the parameter profile of that constructor or method. It specifies the number, the order and the type of the parameters that must be provided in order to correctly invoke that constructor or method.

VOID METHODS vs NON-VOID METHODS


Methods define operations that can be performed on the properties defined in the class. There are two types of methods that can be defined in a class. Those whose return type is void and those whose return type is not void. void Methods These are methods whose return type is void. This means that the method does not return any data back to the statement where that method was invoked. As a result void methods are used as program statements in the invoking program. Example:
/** * class Fraction { * ... * * publ i c increaseBy(int numerator, int denominator) { void * ... * } * * } */ Fraction double myFract ion ; real; // a Fraction

myFraction = new Fraction(); myFraction.increaseBy(1,2);


// / / myFract i on correct ! // i . eincreaseBy() s ta tement for . an

real = myFraction.increaseBy(1,2);

wrong! there i s nothing ign ass to // to output

System.out.println myFraction.increaseBy(1,2) ); / / wrong! there i s nothing ( if ( myFraction.increaseBy(1,2) > 0 ) { / / wrong! there i s nothing to compare System.out.println(Ok! Fraction is POSITIVE!) }

Non-void Methods

These are methods whose return type is any data type primitive or reference type except void. This means that the method returns some data back to the statement where that method was invoked. The data returned can be used as an operand in an arithmetic expression, as an operand in a control expression, or as an argument passed to an invoked method. Example:
/** * class Fraction { * ... * * publ i c double toFloatingPoint { // returns a double value () * return... * } * * } */ Fraction int double myFract ion ; integer; real; // a Fraction

myFraction = new Fraction(); real = myFraction.toFloatingPoint();


real / / correct ! an operand in an ar i thmet i c as / / expression, the double value returned by // toFloatingPoint() will be ass ignedto variable

//

System.out.println myFraction.toFloatingPoint() ); (

// correct! as an argument, // the double value returned by toFloatingPoint() // will be outputtedby println()

if ( myFraction.toFloatingPoint() > 0 ) { // correct! an an operand in a control


// expression, the double value returned by // toFloatingPoint() will be compared to zero

System.out.println(Ok! Fraction is POSITIVE!) } myFraction.toFloatingPoint();


// still valid! toFloatingPoint() will still return // a double value but it will be discarded

integer= myFraction.toFloatingPoint(); // wrong! double value returned by

// toFloatingPoint() method cannot be assigned to // variable integer

integer= ( int) myFraction.toFloatingPoint(); // correct! double value returned


// by toFloatingPoint() method will be typecasted // to int and then assigned to variable integer

SETTERS AND GETTERS FOR PRIVATE PROPERTIES


By default, class properties are visible outside the class where it was defined. Example:
Fraction.java
public class Fraction { public class Client{ public static void main (St r i ng [ ] args) {

Client.java

int numerator; int denominator; ...


}

Fraction

myFraction;

// a Fraction

myFraction = new Fraction(); myFraction.numerator = 3; // valid!

myFract ion .denominator = 5; / / val id !


} }

This may be modified as follows:


Fraction.java
public class Fraction { public class Client{ public static void main (St r i ng [ ] args) {

Client.java

private int numerator ; private int denominator; ...


}

Fraction

myFract ion ;

// a Fraction

myFract ion= new Fraction(); myFract ion .numerator = 3; / / ERROR ! myFraction.denominator = 5; // ERROR!
} }

The same statement myFraction.numerator = 3; and myFraction.denominator = 5; which was previously valid will now result to an error. It becomes an error since declaring a property as private prevents that property to be directly referenced outside the class it can only be directly referenced inside the class. This may be done intentionally if certain restrictions will be enforced on the client program to prevent it from modifying and /or retrieving the value of the private property. Client programs are permitted to modify and/or retrieve these types of properties with the creation of special methods called property setters and property getters. Property Setter usage Used to modify the value of the property
also known as return type method name number of parameters method body
MUTATOR METHOD

Property Getter Used to retrieve the value of the property


ACCESSOR METHOD

void set+name of property One parameter with the same data type as the property Must contain an expression that assigns the parameter to the property

The same data type as the property get+name of property Zero parameters Must contain an expression that return the property

Property Setter Examples


private Str ingname; public void setName (Str ingname) { this.name = name; } private char gender; public void setGender (char gender) { this.gender = gender; } private int age; public void setAge (int age) { this.age = age; } private double speed; public void setSpeed (double speed) { this.speed = speed; }

Property Getter Examples


private Str ingname; public Str inggetName () { return name; private int age; public int getAge () { return age;

} privatechar gender; public char getGender () { return gender; }

} privatedouble speed; public double getSpeed () { return speed; }

OVERLOADED METHODS
In Java, it is possible for several methods to be defined so that they share the same name on the condition that their parameter profiles are different this allows the method to appear flexible to the client program to appear as if a single method accepts different types arguments. Such methods are referred to as OVERLOADED METHODS. Recall that the parameter profile refers to the number, the order and the type of the parameters of a method . Take note that parameter profile does not include the name of the parameters as well as the return type of the method. On the next page are eleven different methods of which only seven are correctly overloaded.

Fraction.java public class Fraction { ... publ i c void add(Fraction other)1 { ... } public void add(Fraction[] others 2 { / / correct ! ) ... } public void add(int num, int den)3 { / / correct ! ... } public void add(int numerator, int denominator) { ... / / wrong! } public void add(int den, int num) { ... } public void add(double real)4 { ... } / / wrong! / / correct ! / / correct !

Parameter Profile

add(Fraction)

add(Fraction[] )

add(int, int)

add(int, int) parameter profile already exists add(int, int) parameter profile already exists add(double )

public void add(int mixed, int num, int den)5 { ... / / correct ! } public int add(int mixed, int num, int den) { ... / / wrong! } public void add(boolean isPositive, int num, int den)6 { ... / / correct ! } public void add(boolean isMixed, int num, int den) { ... / / wrong! } public void add(int num, int den, boolean isMixed)7 { ... / / correct ! } }

add(int, int, int)

add(int, int, int) parameter profile already exists add(boolean, int, int)

add(boolean, int, int) parameter profile already exists add(int, int, boolean)

So that given the seven methods that were correctly overloaded a client program can now use the add() method as follows:
Client.java public class Client { public static void main(String[] args) { Fraction myFraction; Fraction anotherFraction; Fraction[] listOfFractions; ... myFraction = new Fraction();

anotherFract i on new Fract ion( ) ; = l i s tO fF rac t i ons new Fract ion[3] ; = l i s tO fF rac t i ons = new Fract ion( ) ; [0] l i s tO fF rac t i ons = new Fract ion( ) ; [1] l i s tO fF rac t i ons = new Fract ion( ) ; [2] ... myFract ion .add( anotherFraction ); / / correct ! invokes add( Fraction ) myFraction.add( listOfFractions ); // correct! invokes add( Fraction[] ) myFraction.add( 23, 50 ); // correct! invokes add( int, int ) myFraction.add( 0.25 ); // correct! invokesadd( double ) myFraction.add( 6, 2, 3 ); // correct! invokes add( int, int, int ) myFraction.add( true, 1, 2 ); // correct! invokes add( boolean, int, int ) myFraction.add( 1, 2, false ); // correct! invokesadd( int, int, Boolean ) ... myFraction.add( "1/2" ); myFraction.add(); myFraction.add( 1.5, 4 ); } } // wrong! add( String ) is not found // wrong! add() is not found // wrong! add( double, int) is not found

STATIC VS NON-STATIC MEMBERS


As mentioned in one of the earlier sections the properties and methods of a class are referred to as the members of the class. They may be declared as static or non-static. For non-static members, their existence is dependent on the objects that were instantiated from that class. If the object exists (because it was intantiated) then the member exists through the object. If the object no longer exists then the member no longer exists as well. For static members, they exist without the need for objects to be instantiated. Members exist through the class itself. These properties and methods are declared by attaching the word staticduring declaration. Example:
Fraction.java public class Fraction { // static properties stat i cboolean autoReduce = false; // non-static properties private int numerator; private int denominator; boolean isPositive; // static methods public stat i cFraction parseFraction(String strFraction) {
return ...

} public stat i cvoid reduce (Fraction fraction) {


...

} // non-static methods public void setNumerator (int numerator) {


...

public int getNumerator () {


return ...

} public void setDenominator (int denominator) {


...

} public int getDenominator () {


return ...

} public void reduce() {


...

Such that given the definition of the class, the members of the class can be accessed as follows:
/** * class Fraction * * Static Members * - boolean autoReduce * - Fraction parseFraction(String) * - void reduce(Fraction) * * * */ Fract ion myFract ion ; // a Fraction

Non-static Members - boolean isPositive - void setNumerator(int) - int getNumerator() - void setDenominator(int) - int getDenominator() - void reduce()

// accessing static members using the class Fraction Fraction.autoReduce = true; myFract ion = Fraction.parseFraction( "60/100" ); Fraction.reduce ( myFract ion ); // accessing non-static members using the Fraction variable myFraction myFract ion .isPosit ive= true; myFract ion .setNumerator (10); myFract ion .setDenominator (15); myFract ion .reduce (); System.out.println( myFract ion .getNumerator () ); System.out.println( myFract ion .getDenominator () );

Вам также может понравиться