Documente Academic
Documente Profesional
Documente Cultură
Reproduction and/or distribution in whole or in part in electronic, paper or other forms without written permission is prohibited.
Reprinted for Balaji Nallathambi, Verizon Balaji@verizon.com Reprinted with permission as a subscription benefit of Books24x7, http://www.books24x7.com/
Table of Contents
Point 3: Understanding Classes and Objects in Java...................................................................1 Introducing ObjectOriented Programming..................................................................................2 Features of ObjectOriented Programming............................................................................2 Advantages of ObjectOriented Programming.......................................................................2 Creating Classes in Java.................................................................................................................3 Declaring a Class....................................................................................................................3 Creating a Constructor............................................................................................................4 Creating the Data Members....................................................................................................4 Creating the Methods ..............................................................................................................5 Creating Classes: An Example ........................................................................................................7 Creating the main() Method....................................................................................................7 Creating an Object of the Class..............................................................................................7 Implementing Inheritance..............................................................................................................10 Overriding Methods ...............................................................................................................11 Understanding Abstract Classes..................................................................................................13 Additional Information...................................................................................................................14 Related Topics................................................................................................................................15
Declaring a Class
Use the class keyword to declare a class in Java. The syntax to declare a class is:
[<access_specifier>] [<modifier>] class <class_name> { //Code Statements }
In this syntax, access_specifier is optional and determines if other classes can access this class. The valid access specifiers are: public: Allows a class to be accessed by any object in a Java program. private: Allows a class to be accessed by the objects of the same class. Only a class defined inside another class can be declared private. protected: Allows a class to be accessed only by its subclasses. A subclass is a class derived from another class.
Note
If you do not specify an access specifier for a class, then the scope of the class is friendly. A friendly class is accessible to all the classes in a package. A package is a collection of multiple classes that you want to use in an application.
The optional modifier can be either final or abstract. A class that is declared final cannot be inherited while an abstract class must be inherited and implemented. The mandatory class_name can be any valid Java identifier. A valid Java identifier can consist of alphabets, digits, underscore, and the dollar symbol and cannot begin with a digit. For example, the code to declare a public class, Employee, is:
public class Employee { //Code statements }
Note By convention, Java class names are meaningful and begin with an uppercase letter.
Creating a Constructor
A constructor is a method that has the same name as the class. The Java runtime environment invokes the constructor as soon as you create an instance or object of the class. You can use a constructor to initialize the attributes of a class.
Note
The Java runtime environment consists of a compiler to compile Java source files and an interpreter to run compiled Java programs.
For example, if you create a class, Employee, the name of the constructor will also be Employee:
public class Employee { public Employee() { } //Code statements }
Note A method, the conventional Java term for a behavior, is a set of statements used to perform specific functions. For example, a method, draw(), can be used to draw different shapes.
In this syntax, the optional access_specifier determines whether a data member is accessible by other classes. The valid access specifiers are: public: Allows a data member to be accessed by any object in a Java program. private: Allows a data member to be accessed only by the objects of the same class. protected: Allows a data member to be accessed by the subclasses of a given class. Friendly: Allows a data member to be accessed from objects belonging to the same package. Remember that friendly is not a keyword and is the default access.
static: Makes a data member accessible to all the instances of a given class. final: Prevents a data member from being changed after being initialized.
The mandatory datatype specifies the type of data that a data member can contain. Table 132 describes some of the datatypes available in Java: Table 132: Java Datatypes Datatype Byte Short int Long float double boolean char Description Stores 1 byte of data. The range is from 28 to 127. Stores 2 bytes of data. Stores integer values in 4 bytes. Stores integer values in 8 bytes. Stores real numbers with single precision. Stores real numbers with double precision. Stores a Boolean value, true or false. Stores a single character. A char literal is always enclosed within single quotation marks ().
The mandatory var_name specifies a name for the data member. The rules for data member names and class names are same. Conventionally the name of data members begins with a lower case alphabet.
Note
The rules and conventions of data member and methods are same. Conventionally data member names begin with a noun and method names begin with a verb.
For example, to create a class called Employee with data members employeeID, employeeName, and employeeAge, the statements are:
public class Employee { public int employeeID, employeeAge; public string employeeName; }
In this syntax, the optional access_specifier can be public, protected, private or friendly. The rules regarding access specifiers are same for data members and methods. The optional modifier can be static, final, or abstract. A static method can be invoked without creating an object of the class. A final method cannot be redefined by subclass whereas an abstract method must be defined by a subclass. The mandatory return_type specifies the type of data returned by the method. If a method doesnt return any value, the keyword void is used.
Note Remember that no return_type is specified for constructors including void. The mandatory method_name specifies a name for the method. The argument_list defines the values that can be passed to a method. For example, the code to create a method that accepts two integers and adds them is:
public int add(int a, int b) { return a+b; }
The data type, number, and sequence of parameters along with the name form the signature of a method. You cannot define two methods with the same signature in a class. Two methods with the same name but different signature are called overloaded methods. For example, in a class that computes the order value of items bought by a customer, you may need to add two integers, two floats, or one integer and one float. To do so, you can create three methods that accept different types of parameters. In addition, you can provide similar names to all of them. For example, the code for the three add methods are:
public void add(int a, int b); public void add(float a, float b); public void add(int a, float b);
Note When you declare data members and methods, you can interchange the order of the access specifiers and modifiers, which means that the given statements are equivalent.
public static void DispDetails(); static public void DispDetails();
To run the Employee class, you need to create an object of the class. Create this object in the main() method.
This method is declared public so that the Java interpreter can access it. The static modifier specifies that the main method doesnt require an instance of a class for execution. Note There can be only one main() method in a Java program. In addition, the file containing the class with a main() method, must have the same name as the class. For example, if the name of the class containing the main() method is Employee, the name of the file needs to be Employee.java.
For example, to create an object of class Employee, the code statement is:
Employee employeeObject = new Employee();
You can access data members and methods of an object by using the dot operator. For example, to access the storeDetails() method of the object employeeObject of the class Employee the statement is:
Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited
employeeObject.storeDetails();
Similarly, to assign the value 20 to the employeeAge data member, use the statement:
employeeObject.employeeAge=20;
Continuing with the example of the Employee class, the main() method to create an object of the class is:
public static void main(String args[]) { Employee employeeObject=new Employee(); employeeObject.storeDetails(); employeeObject.displayDetails(); }
The Employee.java file containing the Employee class will appear, as shown in Listing 132: Listing 132: The Employee.java File
public class Employee { String employeeName; int employeeID, employeeAge; public void storeDetails() { employeeID = 1; employeeName = "John"; employeeAge = 30; } public void displayDetails() { System.out.println("The ID is: " + employeeID); System.out.println("The Name is: " + employeeName); System.out.println("The Age is: " + employeeAge); } public static void main(String args[]) { Employee employeeObject=new Employee(); employeeObject.storeDetails(); employeeObject.displayDetails(); } }
After saving the class, compile the class by using the javac command from the command prompt as:
javac Employee.java
This will compile the Java source file and create a file with the extension .class as Employee.class. When you execute the class file using the java command, the output appears, as shown in Figure 131:
Implementing Inheritance
Inheritance is the process of deriving a new class from an existing class. For example, Employees can be of two types, permanent and trainee. Both these type of employees have a number of common attributes, such as ID, name, and age. But, the permanent employee would also have a salary attribute, while a trainee would have a stipend attribute. You can derive two classes, PermanentEmployee and Trainee, from the Employee class and add the salary and stipend attributes to the derived classes. Use the extends keyword to inherit a subclass from a superclass. The syntax to do so is:
class <subclass_name> extends <superclass_name> { }
For example, the code statements to create the PermanentEmployee class that extends from the Employee class is:
class PermanentEmployee extends Employee { }
The subclass derives all the attributes and methods from the superclass, except the constructor. This makes the code reusable. For example, a class Employee contains a method displayDetails for displaying employee information. If you create a subclass, PermanentEmployee, the subclass will derive the displayDetails method of the Employee class, as shown in Listing 133:
Listing 133: The PermanentEmp.java File
class Employee { String employeeName; int employeeID, employeeAge; public void displayDetails() { System.out.println("John is an employee of XYZ Inc.!!"); } } public class PermanentEmployee extends Employee { public static void main(String args[]) { PermanentEmployee PE1=new PermanentEmployee(); PE1.DisplayDetails(); } }
When you execute this application, the output appears, as shown in Figure 132, which indicates that using the object of the subclass, PermanentEmployee, you can call the method displayDetails () of the superclass Employee:
11
Figure 132: The PermanentEmployee Class Note There can be only one public class per file. Java also allows you to modify the functionality of a superclass by overriding its methods in the subclass.
Overriding Methods
The process of redefining the superclass methods in a subclass is called overriding. For example, the PermanentEmployee and Trainee classes are derived from the Employee class, which has a method displayDetails(). The type of information may vary depending on whether the employee is permanent or a trainee. As a result, the displayDetails() method is implemented in different ways in the Permanent and Trainee classes. Listing 134 shows the overriding of methods:
Listing 134: The PermanentEmp.java File
class Employee { String employeeName; int employeeID, employeeAge; public void displayDetails() { System.out.println("John is an employee of XYZ Inc.!!"); } } public class PermanentEmployee extends Employee { public void displayDetails() { System.out.println("John is a permanent employee of XYZ Inc.!!"); } public static void main(String args[]) { PermanentEmployee PE1=new PermanentEmployee(); PE1.displayDetails(); } }
12
When you execute this file, the output appears, as shown in Figure 133, which indicates that the displayDetails() method of the PermanentEmployee class is executed:
Figure 133: The PermanentEmployee Class When overriding the methods of a superclass, keep these points in mind:
The signature of the overriding method must be same as the superclass method. The return type of both the overridden and overriding methods must be the same. The overriding method cannot be less accessible than the method it overrides. For example, if the method that overrides is declared as public in the superclass, you cannot override it with the private keyword in the subclass.
Abstract methods are also declared using the abstract modifier and need to be overridden in the subclasses. The syntax to declare an abstract method is:
abstract class automobile { public abstract float rotateWheel(); }
Additional Information
In addition to the static, final, and abstract modifiers, Java provides a number of other modifiers, which are: native: Informs the compiler that the given method is written in a nonJava language, such as C or C++. It can be used only for methods. transient: Prevents data members from being saved to a file. It can be used only for data members. synchronized: Is used for methods in a multithreaded application. volatile: Is used for data members that can be modified simultaneously by many threads.
Related Topics
For related information on this topic, you can refer to: Event and Exception Handling in Java Java Security Model Migrating From C++ to Java Introducing JMF