Saturday, 23 July 2016

Beginning Java Programming Chapter-3

Defining a Method

A method is a self-contained block of code that performs specific operations on the data by using some logic. Defining a method in a program is called method declaration . A method consists of the following elements:
Name : The name identifies the method and is also used to call (execute) the method. Naming a method is governed by the same rules as those for naming a variable, discussed in Chapter 2. • Parameter(s) : A method may have zero or more parameters defined in the parentheses immediately following the method name during the method declaration.
Argument(s) : The parameter values passed in during the method call are called arguments and correspond to the parameters defined during the method declaration.
Return type : A method may optionally return a value as a result of a method call. The type of the data eturned, such as int , is declared in the method declaration.
Access modifier : Each method has a default or specified access modifier, such as public or private , which determines from where the method can be accessed (called). The following is the syntax for writing a method in Java:
<modifier> <returnType> <methodName> ( <Parameters>) {
// body of the method. The code statements go here.
}
The <modifier> specifies the method further, such as its visibility, and <returnType> defines the data type that will be returned by the method. While zero or more modifiers may be used, <returnType> and methodName> are mandatory. The parameters are used to pass data into the method. For example,
consider the following method:
public int square (int number) {
return number*number;
}
The name of the method is square . It will return a value of type int . The modifier public means
it could be called from anywhere. One example of using this method follows: int myNumber = square(2);
After executing this statement, the value of the myNumber variable would be 4.
Note: The method name and return type are mandatory in a method declaration. Even though you are notrequired to specify a modifier in a method declaration, the default modifier is assigned to the
method if you don't declare one.
JavaBeans Naming Standard for Methods A JavaBean is a special kind of Java class that is defined by following certain rules, including the naming conventions for its variables and methods. These rules include the following:
• The private variables of a JavaBean called properties can only be accessed through its getter and setter methods. The naming convention for a property is: the first letter of the first word in the name must be lowercase and the first letter of any subsequent word in the name must be uppercase, e.g., myCow .
• Each non-boolean property has a getter method that is used to retrieve the value of the property. The name of the getter method begins with get followed by the name of the property, with the first letter of each word uppercased.
• Each property has a setter method that is used to set the value of the property. The name of the setter method begins with set followed by the name of the property, with the first letter of each word uppercased.
• The getter and setter methods must be public so that anyone who uses the bean can invoke them.
• A setter method must have the void return type and must have a parameter that represents the type of the corresponding property.
• A getter method does not have any parameter and its return type matches the argument type of the corresponding setter method. The following code fragment illustrates these rules:
public class ScoreBean {
private double meanScore;
// getter method for property meanScore
public double getMeanScore() {
return meanScore;
}
// setter method to set the value of the property meanScore
public void setMeanScore(double score) {
meanScore = score;
}
}
Note : that two methods, getMeanScore() and setMeanScore(…) , correspond to the variable (property) meanScore . The main motivation for standardizing the naming in JavaBeans is to enable you to use some components (JavaBeans in this case) developed by other developers so that you don't have to develop the whole application code from scratch. The implementation of a naming standard in your application and in the components ensures that the development and deployment tools can recognize and use the components developed by other developers. So, the methods can be static or nonstatic, and they may have a fixed number of parameters or a variable number of parameters. Just like a variable, a method is a member of a class; in other words, it is written inside a class. Class and Object
The class is the basis for object-oriented programming. The data and the operations on the data are encapsulated in a class. In other words, a class is a template that contains the data variables and the methods that operate on those data variables following some logic. So, the class is the foundation on which the entire Java language is built.
All the programming activity happens inside classes. The data variables and the methods in a class are called class members. Variables, which hold the data (or point to it in case of reference variables), are said to represent the state of an object (that may be created out of the class), and the methods constitute its behavior. In This section, we explore writing classes and creating objects from them. Defining Classes A class is declared by using the keyword class . The general syntax for a class declaration is
<modifier> class <className> { }
<className> specifies the name of the class, class is the keyword, and <modifier> specifies some characteristics of the class. The <modifier> specification is optional, but the other two elements in the declaration are mandatory. You can broadly group the modifiers into the following two categories:
Access modifiers : Determine from where the class can be accessed: private , protected , and public . If you do not specify an access modifier, the default access is assumed.
Other modifiers : Specify how the class can be used: abstract , final , and strictfp . As an example of an access modifier, consider the following class declaration: class MyClass { }
¦ Note The keyword class and class name are mandatory in a class declaration. Even though you are not required to specify a modifier in a class declaration, the default modifier is assigned to the class, if you don't declare one.
Because no access modifier is declared in the preceding class declaration, the default access is assumed. As an example of a non-access modifier, you can declare an abstract class by specifying
the abstract modifier, as in the following: abstract class MyClass { } Creating an Object
The object is created in the following line of code:
ClassRoom roomOne = new ClassRoom();
What is happens here:
• The left side declares a reference variable roomOne of class ClassRoom .
• The right side creates an object of class ClassRoom with the operator new .
• The assignment operator = assigns the newly created object to the reference variable roomOne . Nested Classes All the classes discussed so far fall into a category called top-level classes. Java also allows you to define a class inside a top-level class. This kind of class is called a nested class. In this context, the top-level class is also called an outer class or enclosing class. A nested class is a member (like a variable or a method) of another class.
It would look like the following:
class <OuterClassName> {
// variables and methods for the outer class
class <NestedClassName> {
// variables and methods for the nested class
} }
As you already know, a class member can be static or nonstatic. A nonstatic nested class is also called an inner class, while a static nested class is called, well, a static nested class.
¦ Note A nested class is a class that is a member of another class. A nonstatic nested class is called an inner class, and its instance has direct access to instance variables and methods of the outer class instance.
You write inner classes only when a relationship between two objects in the real problem requires it—for example, when the inner class makes sense only in the context of the outer class, or it depends upon the outer class in its functionality. Following are the salient features of the nested classes:
• An inner class (nonstatic nested class) is associated with an instance of its outer class.
• Unlike an external class, an inner class has unlimited access to the members of the outer class, including the private members, because the inner class itself is a member of the outer class.
• Just like the static variables and methods of the outer class (also called class variables and methods), the scope of the static nested class is the outer class, and not just one instance. Therefore, just like static methods in the outer class, you cannot access directly the nonstatic variables or methods of the outer class from inside the static nested class.
• Because an inner class, being a nonstatic member, is associated only with an instance of its outer class, you cannot define a static member inside an inner class.
• An instance of an inner class can only exist within an instance of its outer class, just like any other nonstatic member of the outer class.
• Nested classes can be declared abstract or final , just like any other class and with the same meaning.
• The access modifiers, such as public , private , and protected , can be used for inner classes just like with other members of the outer class and with the same meaning.
• Any nested class can be declared in any block of code such as a class or a method.
• A nested class declared within any block of code, such as a method, will have access to any local (including final) variables within the scope of the block. Enum introduced in J2SE 5.0, is useful when you want a variable to hold only a predetermined set of values. You should use enums any time you need a fixed set of constants, including natural enumerated types such as days of the week. You define an enum variable in two steps:
1. Define the enum type with a set of named values.
2. Define a variable to hold one of those values.
 
Following is an example:
The enum AllowedCreditCard {VISA, MASTER_CARD, AMERICAN_EXPRESS};
AllowedCreditCard visa = AllowedCreditCard.VISA;
You can think of enum as an alternative to defining a regular class, or you can think of it as a special kind of class. In other words, it has differences and similarities with the regular Java class. The preceding code defines a class named AllowedCreditCard with the restriction that you can create only three instances (a regular class does not have such a restriction) of this class, corresponding to each value defined in the curly braces. However, just like a normal class, a public enum must be in a file named after the enum name. A value stored in an instance of an enum is retrieved by referring to it just like a variable, as shown in this example:
System.out.println("The allowed credit card value: " + visa)
Any enum type you declare inherits some methods that you can use.
Methods of the Enum Class
final boolean equals(Object obj)
Returns true if the object passed in as an argument is equal to this enum constant.
final String name()
Returns the name of this enum constant exactly as in the enum declaration.
String toString()
Returns the name of this enum constant exactly as in the enum declaration. You can override this method, but not the name() method.
static Enum valueOf(Class enumClass, String name)
Returns the enum constant of the specified enum class with the specified name. Inheritance Inheritance is a fundamental feature of object-oriented programming. It enables the programmer to write a class based on an already existing class. The already existing class is called the parent class, or superclass, and the new class is called the subclass, or derived class. The subclass inherits (reuses) the nonprivate members (methods and variables) of the uperclass, and may define its own members as well. Inheritance facilitates the reuse of code and helps to adapt rogramming to real-world situations. For example, consider a class named ClassRoom whose members represent general properties (and behavior) of a classroom. A specific classroom may have additional members to further specify the lassroom. For example, a computer lab used by a teacher for a hands-on class is a classroom. So is a lecture hall with no computers in it. Instead of writing the class ComputerLab from scratch, you can derive it from the class ClassRoom . The keyword to derive a class from another class is extends . The declaration looks like this:
class ComputerLab extends ClassRoom { .................}
1. class TestComputerLab {
2. public static void main(String[] args) {
3. ComputerLab cslab = new ComputerLab();
4. cslab.printSeatInfo();
5. System.out.println("Total seats in the class room:
"+cslab.getTotalSeats());
6. }
7. }
8. // Class ComputerLab
9. class ComputerLab extends ClassRoom {
10. int totalComputers = 30;
11. String labAssistant="TBA";
12. void printSeatInfo() {
13. System.out.println("There are " + getTotalSeats() + " seats, and "+
totalComputers + " computers in this computer lab.");
15. }
16. String getLabAssistant(){
17. return labAssistant;
18. }
19. void setLabAssistant(String assistant){
20. this.labAssistant = assistant;
21. }
22. }
In line 9, the ComputerLab class extends the ClassRoom class. The TestComputerLab class (lines 1 to 7) is used to test the ComputerLab class, which uses an inherited method of the ClassRoom class ( getTotalSeats() in line 13) and defines a couple of its own methods: getLabAssistant() and setLabAssistant() .
The Output Will Be
There are 60 seats, and 30 computers in this computer lab. Total seats in the class room: 60 Writing and Invoking Constructors When you instantiate a class, the resulting object is stored in memory. Two elements are involved in allocating and initializing memory for an object in Java: the new operator, and a special method called a constructor. The constructor of a class has the same name as the class and has no explicit return type. When the Java runtime system encounters a statement with the new operator, it allocates memory for that instance. Subsequently, it executes the constructor to initialize the memory. For example, consider the following line of code:
ComputerLab csLab = new ComputerLab();
This statement includes the operator new and a special method ComputerLab() , which has the same name as the class ComputerLab . This special method is called a constructor, the default noargument constructor of a class. When the Java runtime system encounters this statement, it does the following, and in this order:
1. Allocates memory for an instance of class ComputerLab
2. Initializes the instance variables of class ComputerLab
3. Executes the constructor ComputerLab()
Note: If a class does not have any constructor defined, the compiler provides the constructor with no parameters, called the default constructor. If a class has at least one constructor defined, the compiler does not provide the default onstructor.
In addition to the constructor (with no parameters), you can also define nondefault constructors with parameters. However, the constructor name stays the same: the class name. The constructor may be called from inside the class where it is defined or from outside the class, using the following rules:
• Outside of the class in which a constructor is defined, the constructor can be called only with the new operator, that is, when you want to create an instance of the class. For example, a code expression new A() in the class B will create an instance of the class A .
• Inside the class where a constructor is defined, the constructor can be called from within another constructor, and not from anywhere else.
From inside a constructor of a class, you can call another constructor of the same class, or a constructor of the superclass. You use the keyword this to call another constructor in the same class, and use the keyword super to call a constructor in the superclass. If you use either this or super , it must appear in the beginning of the code block of the constructor. If you add your own super or this call, then the compiler will not add the line super() . With regard to including super or this in the constructor, three possible cases exist:
• If you include neither a super call nor a this call, the compiler places a super call in the beginning of the constructor's body.
• If you include a super call with or without arguments, the compiler adds no super call to the code.
• If you include this to make a call to another constructor in the same class, the other constructor would have either an explicit this call in the beginning of the code block or an explicit or implicit (added by the compiler) super call. If the other constructor had a this call, then at the end of this chain, a super call would be made eventually.
The preceding discussion shows that before executing the body of a constructor in a class that is being instantiated, a constructor in the superclass must be executed. In other words, the superclass is initialized before executing the body of the constructor in the class that is being instantiated. This would make sure that the instance variables of both the current class and the superclass are initialized before the constructor body is executed.
¦ Note If you don't make a this or super call in the beginning of a constructor, the compiler places a super call there.
To illustrate some of these points, consider Code
1. class TestConstructors {
2. public static void main(String[] args) {
3. new MySubSubClass();
4. }
5.
6. }
7. // Class MySuperClass
8. class MySuperClass {
9. int superVar = 10;
10. MySuperClass(){
11. System.out.println("superVar: " + superVar);
12. }
13. MySuperClass(String message) {
14. System.out.println(message + ": " + superVar);
15. }
16. }
17. // Class MySubClass inherits from MySuperClass
18. class MySubClass extends MySuperClass {
19. int subVar = 20;
20. MySubClass() {
21. super("non default super called");
22. System.out.println("subVar: " + subVar);
23. }
24. }
25. // Class MySubSubClass inherits from MySubClass
26. class MySubSubClass extends MySubClass {
27. int subSubVar = 30;
28. MySubSubClass() {
29. this("A non-deafult constructor of MySubSubClass");
30. System.out.println("subSubVar: " + subSubVar);
31. }
32. MySubSubClass(String message){
33. System.out.println(message);
34. }
35. }
the class MySubSubClass (line 26) extends MySubClass (line 18), which in turn extends MySuperClass (line 8). The class MySubSubClass is instantiated (line 3) in the class TestConstructors (line 1). If you compile and execute this code, you receive the following output:
non default super called:10
subVar: 20
A non default constructor of MySubSubClass
subSubVar: 30
Now, let's see what happened to generate this output. As a result of executing line 3, the MySubSubClass() constructor (line 28) was called, which in turn called the MySubSubClass(String message) constructor (line 32) due to the this call (line 29). Because the MySubSubClass(String message) constructor had no this or super call in the beginning of its body, the compiler placed a super() call there. As a result, this constructor first calls the MySubClass() constructor (line 20), which, due to a super call (line 21), calls the MySuperClass(String message) constructor, which in turn produces the first line of output. After that, the execution control returns to line 22, which generates the second line of the output. Subsequently, lines 33 and 30 are executed, generating the third and fourth lines of the output, respectively. .
It is important to understand the flow of execution control from constructor to constructor when a class is instantiated. There is another very interesting scenario to consider. Assume that you write a superclass only with a constructor with parameters (therefore, the compiler will not provide the default constructor). Now, if a constructor in the subclass of this superclass makes the super() call, it will generate a compiler error, because the default constructor of the superclass does not exist. For example, consider the following code fragment:
class A {
int myNumber;
A(int i) {
myNumber = i;
} }
class B extends A {
String myName;
B (String name) {
myName = name;
} }
This code will generate a compiler error, and here is why. The compiler will add the super() call in the beginning of the code body of the constructor B(String name) of class B . This would be a call to the default constructor of class A . However, the compiler did not create the default constructor for A because A already had a nondefault constructor. Therefore, the compiler will generate an error. One way to fix this problem is to add a default constructor to class A manually.
The key points about constructors are summarized here:
• A constructor of a class has the same name as the class, and has no explicit return type.
• A class may have more than one constructor. If the programmer defines no constructor in a class, the compiler will add the default constructor with no arguments. If there are one or more constructors defined in the class, the compiler will not provide any constructor.
• A constructor may have zero or more parameters.
• From outside the class, a constructor is always called with the new operator. From inside the class, it may be called from another constructor with the this or super operator— this to call another constructor of the same class, super to call a constructor of the superclass. The super or this call is always made in the beginning of the constructor body.
• Unlike other methods, the constructors are not inherited. If the superclass has constructors and the subclass does not, the compiler assumes that the subclass does not have any constructor and creates the default constructor.
• If there is no super call in a constructor, the default super call is placed by the compiler, that is, a call to the default constructor of the superclass.
A key point to remember here is that before the variables of a class are initialized, the variables
of its parent class must be initialized, and this is accomplished by a chain of constructor calls. As
you already know by now, a class can inherit only from one class, but it can inherit from more than
one interface.
Writing and Using Interfaces
Java supports single inheritance. That means a subclass in Java can have only one superclass. However, if multiple inheritance is needed, Java provides a solution: use an interface. While a subclass can inherit only from one superclass, it can also inherit from one or more interfaces in addition to the superclass. An interface is a template that contains some method declarations. The interface provides only declarations for the methods, and no implementation. The class that inherits from an interface must provide the implementation for the methods declared in the interface.
¦ Note An interface contains method declarations, and a class that implements the interface must provide implementation for its methods.
You define an interface by using the keyword interface , as shown in the following:
interface <InterfaceName> {
<dataType1> <var1>;
<dataType2> <var2>;
<ReturnType1> <methodName1> ( );
<ReturnType2> <methodName2>(<parameters>);
} // interface definition ends here.
The methods declared in an interface are implicitly public and abstract . Therefore, when you implement them in a class, you must declare them public . The data variables declared in an interface are inherently constants and are visible from all the instances of the class that implements the interface. In other words, they are inherently public , final , and static .
¦ Note When you implement a method of an interface, you must declare it public in your class, because all the interface methods are implicitly public . The data variables in an interface are inherently public , final , and static .
There are a few more features of interfaces related to inheritance and implementation:
• A class can extend (inherit from) another class (only one) by using the keyword extends , but it can inherit from one or more interfaces by using the keyword implements .
• Just like a class, an interface can also extend one or more interfaces by using the keyword extends .
• An interface cannot implement any interface or class.
1. interface ParentOne {
2. int pOne = 1;
3. void printParentOne();
4. }
5. interface ParentTwo {
6. int pTwo = 2;
7. void printParentTwo();
8. }
9. interface Child extends ParentOne, ParentTwo{
10. int child = 3;
11. void printChild();
12. }
13.
14. class InheritClass implements Child {
15. public void printParentOne(){
16. System.out.println(pOne);
17. }
18. public void printParentTwo(){
19. System.out.println(pTwo);
20. }
21. public void printChild(){
22. System.out.println(child);
23. }
24. }
25. class TestInterface {
26. public static void main(String[] args){
27. InheritClass ic = new InheritClass();
28. ic.printParentOne();
29. ic.printParentTwo();
30. ic.printChild();
31. }
32. }
The following is the output from this code: 1 2 3
If class A extends another class, B , and implements an interface, C , the syntax will be
class A extends B implements C {}
Note that extends must come before implements . Also note that the methods declared in the interfaces are declared public in the class InheritClass in which they are implemented (lines 15, 18,and 21). If you remove the keyword public from any of these methods, the code will not compile. If you, for example, prepend the method declaration for printParentOne (line 3) with the modifier protected or private , the code will not compile, either. However, if you prepend the declaration with the modifier public , the code will compile; but you don't need to do that because a method declared in an interface is inherently public .
The important points about interfaces are summarized here:
• An interface must be declared with the keyword interface .
• All interface variables are inherently public , static , and final .
• All interface methods are inherently public and abstract . This means they must be implemented in the class that implements the interface and declared public in there. That is, all the interface methods must be implemented by the class that implements the interface unless the class is abstract .
• Because interface methods are inherently abstract , they cannot be declared final , native , strictfp , or synchronized .
• A class can extend another class and implement one or more interfaces at the same time.
• An interface can extend one or more interfaces. An interface cannot extend a class, just another interface.
• An interface cannot implement another interface or class.
¦ Note A class can extend another class by using the keyword extends , implement one or more interfaces by using the keyword implements , or do both. An interface can extend another interface but cannot implement it. Also, an interface cannot implement any class.
The three most important takeaways from this chapter are the following:
• A Java program consists of classes, and a class usually consists of methods and variables, but it can also contain another class, called a nested class.
• The methods in a class can be static or nonstatic, and a static method can only access the static members of the class.
• A class can extend only one class, but it can implement one or more interfaces in addition to extending one class. An interface can extend one or more interfaces, but it cannot implement any interface or class.

Beginning Java Programming Chapter 4

No comments:

Post a Comment