Imagine you are writing a program for a business that sells flowers:
Consider the following program: class Flower { int type; int color; char arrangement; double unitPrice; } public class Exercise { static void main(String[] args) { Flower flr = new Flower(); System.out.println("Flower Type: " + flr.type); System.out.println("Flower Color: " + flr.color); System.out.println("Arrangement: " + flr.arrangement); System.out.printf("Price: %.2f", flr.unitPrice); } } This would produce: Flower Type: 0 Flower Color: 0 Arrangement: Price: 0.00 If you declare a variable of a class in your program, when the program comes up, the compiler reserves enough memory space for each member of the class. The memory space reserved for each member variable is filled with an initial value based on its type. For a String or a char field, the space would be left empty. For an integer type, the space would be filled with 0. A better way to take care of this is to provide a value whose role would be to initialize the member variables with the values of your choice. A method that initializes an object can return any value but it is preferable to be of type void because its primary purpose is to reset the values. Since this method would give a starting value to all member variables that need to be initialized, it should have an equivalent argument for each of the member variables that it would initialize. Here is an example: public class Flower { int type; int color; char arrangement; double unitPrice; void initializer(int tp, int clr, char arng, double price) { } } The method initializer does not have to initialize all members of the class. For example, the previous execution of the program showed that the member variables that are of type String or char are initialized with an empty string or character. In such a case, you may not have to initialize such variables. To implement a method initializer, simply assign its argument to the corresponding member variable of the class. Here are examples: public class Flower { int type; int color; char arrangement; double unitPrice; void initializer(int tp, int clr, char arng, double price) { type = tp; color = clr; arrangement = arng; unitPrice = price; } } You can call a method initializer after declaring the instance of the class to give it initial values. Here is an example: class Flower { int type; int color; char arrangement; double unitPrice; void initializer(int tp, int clr, char arng, double price) { type = tp; color = clr; arrangement = arng; unitPrice = price; } } public class Exercise { static void main(String[] args) { Flower flr = new Flower(); flr.initializer(3, 7, 'V', 45.95D); System.out.println("Flower Type: " + flr.type); System.out.println("Flower Color: " + flr.color); System.out.println("Arrangement: " + flr.arrangement); System.out.printf("Price: %.2f", flr.unitPrice); } } This would produce: Flower Type: 3 Flower Color: 7 Arrangement: V Price: $45.95 Using a method initializer, after initializing the object, you can use the values it holds as you see fit.
A constructor is a special method that is created when the object comes to life. This particular method holds the same name as the class and it initializes the object whenever that object is created. When you create a class, if you do not create a constructor, the compiler creates one for you; this is useful because it lets all other objects of the program know that the object exists. This compiler-created constructor is called the default constructor. If you want, you can create your own constructor. To create a constructor, declare a method that holds the same name as the class. The method must not return any value. Here is an example: class Flower { Flower() { } } When you declare an instance of the class, whether you use that object or not, a constructor for the object is created. When an instance of a class has been declared, the default constructor is called, whether the object is used or not. This is illustrated in the following program: class Flower { int type; int color; char arrangement; double unitPrice; Flower() { System.out.println("New Flower Order"); } } public class Exercise { static void main(String[] args) { Flower flr = new Flower(); } } This would produce: New Flower Order As you can see, even though the flr variable was not used, just its declaration was enough to signal it. You might find it sometimes convenient to create your own constructor because, whether you create an empty constructor or not, this does not negatively impact your program.
A constructor can be used to initialize the fields of a class. As such, a constructor provides a valuable alternative to a method initializer, the type of method we saw earlier. To use a constructor to initialize the member variables of a class, provide as arguments the necessary variables that you intend to initialize. You don't have to initialize all member variables in the constructor, only those that need to be initialized. In fact, you should initialize only those members that you think the other objects would need when using this object. This means that your object may have fields that, either the external objects don't need to modify (or access) or the member variable(s) will be initialized later when called from the needed object(s). To implement a default constructor, you can just initialize the desired members of the class. For a member variable of a numeric type, you can just assign the desired constant to each. If the variable is a character, assign a single-quoted symbol to it. If the variable is a string, then assign a double-quoted value to the variable. Here are examples: class Flower { int type; int color; char arrangement; double unitPrice; Flower() { type = 1; color = 1; arrangement = 'V'; unitPrice = 0D; } } public class Exercise { static void main(String[] args) { Flower flr = new Flower(); System.out.println("Flower Type: " + flr.type); System.out.println("Flower Color: " + flr.color); System.out.println("Arrangement: " + flr.arrangement); System.out.printf("Price: %.2f", flr.unitPrice); } } This would produce: Flower Type: 1 Flower Color: 1 Arrangement: V Price: 0.00
The default constructor is the favorite place to provide default values to the fields of a class. Besides the default constructor, you can add as many constructors as you judge necessary. This feature allows you to create various constructors for different reasons. This also means that the methods or constructors of a class can be overloaded. One of the rules of method overloading consists of having methods with different types of arguments. The most basic constructor you would create can use a single argument. When implementing a constructor that takes one argument, you should initialize the member that corresponds to the unique argument and initialize the other members with default values. Here is an example: class Flower { int type; int color; char arrangement; double unitPrice; Flower(int tp) { type = tp; color = 1; arrangement = 'V'; unitPrice = 0D; } } If you create a class with only one constructor as in the current example, when declaring an instance of the class, you must use that constructor: you cannot use the default constructor that does not take an argument. When declaring the variable, initialize it with a constructor with parentheses and provide the value(s) in the parentheses of the constructor. Here is an example: class Flower { String type; String color; String arrangement; double unitPrice; Flower(String tp) { type = tp; color = "Red"; arrangement = "Basket"; unitPrice = 55.95D; } } public class Exercise { static void main(String[] args) { Flower flr = new Flower("Tulips"); System.out.println("Flower Type: " + flr.type); System.out.println("Flower Color: " + flr.color); System.out.println("Arrangement: " + flr.arrangement); System.out.printf("Price: %.2f", flr.unitPrice); } } This would produce: Flower Type: Tulips Flower Color: Red Arrangement: Basket Price: $35.95 In the same way, you can create different constructors for different initializations, although it would not be realistic to create a different constructor for each variable. If you create different constructors with different arguments to initialize (remember the rules of method overloading) the objects, when declaring the classes, make sure you initialize each instance with the right number of arguments; otherwise, the compiler would complain. If you create a class with only one constructor and that constructor has at least one argument, the default constructor would not be available anymore. If you want to access a default constructor of an object, you have two alternatives:
A class can be created inside of another class. A class created inside of another is referred to as nested. To nest a class, simply create it as you would any other. Here is an example of a class called Inside that is nested in a class called Outside: public class Outside { public class Inside { } } In the same way, you can nest as many classes as you wish in another class and you can nest as many classes inside of other nested classes if you judge it necessary. Just as you would manage any other class so can you exercise control on a nested class. For example, you can declare all necessary fields, properties, or methods in the nested class or in the nesting class. Here is an example: public class Outside { public class Inside { Inside() { System.out.println(" -= Inside =-"); } } Outside() { System.out.println(" =- Outside -="); } }
Just like any of the variables we have used so far, you can make a class a member variable of another class. To use a class in your own class, of course you must have that class. You can use one of the built-in classes of the Java language or you can first create your own class. Here is an example of a class: class Point { int x; int y; } A field is a member variable created from another class instead of a primitive type. To use one class as a member variable of another class, simply declare its variable as you would proceed with any of the member variables we have declared so far. Here is an example: class Point { int x; int y; } public class CoordinateSystem { Point ptStart; } After a class has been declared as a member variable of another class, it can be used regularly. Because the member is a class, declared as a reference, there are some rules you must follow to use it. After declaring the member variable, you must make sure you have allocated memory for it. You must also make sure that the variable is initialized appropriately before it can be used; otherwise you would receive an error when compiling the program.
Like a value from a regular type, you can return a class value from a method of a class. To do this, you can first declare the method and specify the class as the return type. Here is an example: class Point { int x; int y; } public class CoordinateSystem { Point ptStart; Point ptEnd; Point getThePoint() { } } After implementing the method, you must return a value that is conform to the class, otherwise you would receive an error when compiling the application. You can proceed by declaring a variable of the class in the body of the method, initializing the variable, and then returning it. Here is an example: class Point { int x; int y; } public class CoordinateSystem { Point ptStart; Point ptEnd; Point getThePoint() { Scanner scnr = new Scanner(System.in); Point pt = new Point(); System.out.print("Enter the x coordinate of the point: "); pt.x = scnr.nextShort(); System.out.print("Enter the y coordinate of the point: "); pt.y = scnr.nextShort(); return pt; } } Once a method has returned a value of a class, the value can be used as normally as possible.
Once a class has been created, it can be used like any other variable. For example, its variable can be passed as argument to a method of another class. When a class is passed as argument, its members are available to the method that uses it. Here is an example: import java.util.Scanner; class Point { int x; int y; } class CoordinateSystem { Point ptStart; Point ptEnd; Point getThePoint() { Scanner scnr = new Scanner(System.in); Point pt = new Point(); System.out.print("Enter the x coordinate of the point: "); pt.x = scnr.nextInt(); System.out.print("Enter the y coordinate of the point: "); pt.y = scnr.nextInt(); return pt; } } public class Exercise { static CoordinateSystem identifyCoordinates() { CoordinateSystem coord = new CoordinateSystem(); System.out.println("Start Point"); coord.ptStart = coord.getThePoint(); System.out.println("End Point"); coord.ptEnd = coord.getThePoint(); return coord; } static void show(CoordinateSystem c) { System.out.println("Coordinate System"); System.out.printf("Starting Point: P(%d, %d)", c.ptStart.x, c.ptStart.y); System.out.println(); System.out.printf("Ending Point: Q(%d, %d)", c.ptEnd.x, c.ptEnd.y); } static void main(String[] args) { CoordinateSystem coord = identifyCoordinates(); show(coord); } } Here is an example of running the program: Start Point Enter the x coordinate of the point: 1 Enter the y coordinate of the point: 5 End Point Enter the x coordinate of the point: 2 Enter the y coordinate of the point: 5 Coordinate System Starting Point: P(1, 5)Ending Point: Q(2, 5) As done for the arguments of primitive types, you can pass more than one class as argument to a method. Because classes are always used as references, when passing a class as argument, it is implied to be passed by reference.
An instance of a class can be passed as an argument to one of its own methods (if you have programmed in C++, an example of this implementation is the copy constructor; although you can legitimately create a copy constructor in Java, it does not have the exact same concept as in C++). To do this, you primarily pass the argument as if it were any class. Here is an example: class Point { int x; int y; void equivalent(Point same) { } } Then, in the body of the method, do whatever you want. You can, or you may not, use the argument. Still, if you decide to use the argument, know that all of the other members of the class are available through the argument. Probably the simplest way to use the argument is the assign each of of its values to the equivalent member of the class. Here is an example: class Point { int x; int y; void equivalent(Point same) { this.x = same.x; this.y = same.y; } } When calling the method, make sure you pass an instance of the class to it. You can first create and define the class, then pass it. Here is an example: class Point { int x; int y; void equivalent(Point same) { this.x = same.x; this.y = same.y; } } public class Exercise { static void showPoint(Point pt) { System.out.print("Point Coordinates: "); System.out.printf("A(%d, %d)", pt.x, pt.y); } static void main(String[] args) { Point pt = new Point(); pt.x = 4; pt.y = 6; showPoint(pt); System.out.println(); Point one = new Point(); one.equivalent(pt); showPoint(one); } } This would produce: Point Coordinates: A(4, 6) Point Coordinates: A(4, 6) Instead of first declaring a variable of the class and initializing it, you can create an instance of the class in the parentheses of the calling method. To do this, you may need a constructor that can specify the values of the fields of the class so the argument can be rightfully initialized. Here is an example: class Point { int x; int y; Point() { } Point(int xCoord, int yCoord) { this.x = xCoord; this.y = yCoord; } void equivalent(Point same) { this.x = same.x; this.y = same.y; } } public class Exercise { static void showPoint(Point pt) { System.out.print("Point Coordinates: "); System.out.printf("A(%d, %d)", pt.x, pt.y); } static void main(String[] args) { Point pt = new Point(); pt.x = 4; pt.y = 6; showPoint(pt); System.out.println(); Point one = new Point(); one.equivalent(new Point(-3, 2)); showPoint(one); } } Instead of a formal method, you can use a constructor of the class to pass an instance of the same class. Then, in the constructor, use the argument as you see fit, knowing that all the members of the class are available. Here is an example: class Point { int x; int y; Point() { } Point(int xCoord, int yCoord) { this.x = xCoord; this.y = yCoord; } Point(Point same) { this.x = same.x; this.y = same.y; } } Obviously the purpose of passing a class to one of its own methods is not to find its equivalent. Instead, you can create a method that takes an instance of the same class but modifies that instance. For example, for our Point class, we may want to create a new point that is distanced by one unit from the current Point object. Here is an example of doing that: class Point { int x; int y; Point() { } Point(int xCoord, int yCoord) { this.x = xCoord; this.y = yCoord; } void equivalent(Point same) { this.x = same.x; this.y = same.y; } void createPointOneUnitAway(Point addUnit) { this.x = addUnit.x + 1; this.y = addUnit.y + 1; } } public class Exercise { static void showPoint(Point pt) { System.out.print("Point Coordinates: "); System.out.printf("A(%d, %d)", pt.x, pt.y); } static void main(String[] args) { Point pt = new Point(); pt.x = 4; pt.y = 6; showPoint(pt); System.out.println(); Point one = new Point(); one.createPointOneUnitAway(pt); showPoint(one); System.out.println(); one.createPointOneUnitAway(new Point(-8, -3)); showPoint(one); } } This would produce: Point Coordinates: A(4, 6) Point Coordinates: A(5, 7) Point Coordinates: A(-7, -2)
You can create a method in a class that returns an instance of the class. To start, on the left side of the method, enter the name of the class. Here is an example: class Point { Point MethodName() { } } There are various ways you can deal with the method. If you want to return a new value of the class, you can declare an instance of the class, initialize it, and then return it. Here is an example: class Point { int x; int y; Point() { } Point(int xCoord, int yCoord) { this.x = xCoord; this.y = yCoord; } Point(Point same) { this.x = same.x; this.x = same.x; } Point advanceBy5() { Point some = new Point(); some.x = 5; some.y = 5; return some; } } public class Exercise { static void showPoint(Point pt) { System.out.print("Point Coordinates: "); System.out.printf("A(%d, %d)", pt.x, pt.y); } static void main(String[] args) { Point pt = new Point(); pt.x = 4; pt.y = 6; showPoint(pt); Point away5 = pt.advanceBy5(); showPoint(away5); } } This would produce: Point Coordinates: A(4, 6) Point Coordinates: A(5, 5) Alternatively, you can declare an instance of the class, use the current values of the class combined with those of the instance to get new values, and then return the instance. Here is an example: class Point { int x; int y; Point() { } Point(int xCoord, int yCoord) { this.x = xCoord; this.y = yCoord; } Point(Point same) { this.x = same.x; this.x = same.x; } Point advanceBy5() { Point some = new Point(); some.x = this.x + 5; some.y = this.y + 5; return some; } } public class Exercise { static void showPoint(Point pt) { System.out.print("Point Coordinates: "); System.out.printf("A(%d, %d)", pt.x, pt.y); } static void main(String[] args) { Point pt = new Point(); pt.x = 4; pt.y = 6; showPoint(pt); System.out.println(); Point away5 = pt.advanceBy5(); showPoint(away5); } } This would produce: Point Coordinates: A(4, 6) Point Coordinates: A(9, 11) Remember that, to call the method, if it is not static, you will need to declare an instance of the class from where you are calling the method. The second type of implementation consists of modifying the instance of the class that is calling the method. For example, you can add values to its fields or you can perform any other operation you want on the members of the calling instance. is an example: class Point { int x; int y; Point() { } Point(int xCoord, int yCoord) { this.x = xCoord; this.y = yCoord; } Point(Point same) { this.x = same.x; this.x = same.x; } // This method adds 1 to each field of the class // to get a new point away North-East of the current point Point createPointOneUnitAway() { this.x = this.x + 1; this.y = this.y + 1; return this; } } public class Exercise { static void showPoint(Point pt) { System.out.print("Point Coordinates: "); System.out.printf("A(%d, %d)", pt.x, pt.y); } static void main(String[] args) { Point pt = new Point(); pt.x = 4; pt.y = 6; showPoint(pt); System.out.println(); Point one = new Point(-8, 5); Point another = one.createPointOneUnitAway(); showPoint(another); } } This would produce: Point Coordinates: A(4, 6) Point Coordinates: A(-7, 6) As we have learned now, you can create a method that takes an argument that is the same type as its parent class. In the method, you can access any member of the class, including calling the other methods of the class. |
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|