Sunteți pe pagina 1din 17

All rights reserved.

Reproduction and/or distribution in whole or in part in electronic, paper or other forms without written permission is prohibited.

Java ReferencePoint Suite


SkillSoft Corporation. (c) 2002. Copying 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

Point 3: Understanding Classes and Objects in Java


Manisha Singhal Objectoriented languages use classes and objects. Java is an objectoriented programming language that allows you to define and use classes in your programs. All applications written in Java contain code organized in classes. This ReferencePoint discusses the concept of classes and objects and their use in Java programs.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Introducing ObjectOriented Programming


Objects are entities of a particular type with common features. For example, a pen, a mobile phone, or an individual human being are all objects. All objects have attributes, behaviors, and states. Attributes are specific properties of an object. For example, a mobile phone can have attributes, such as the name of the device, the memory available, and color of the device. Behaviors are actions that an object can perform. For example, a mobile phone can connect to a network, ring, dial a number, and change tone. State is a snapshot of an object at a given instance of time. For example, a mobile phone can have states, such as ringing, dialing, and switched off. A class is a template for a group of objects that share common attributes and behaviors. For example, all human beings belong to the same class because they have common attributes, such as height, weight, nose, eyes and common behaviors, such as walking, talking, and thinking. Classes and objects together form the building blocks of objectoriented programming.

Features of ObjectOriented Programming


As a result of the use of objects and classes, all objectoriented programs have common features as described in Table 131: Table 131: Objectoriented Programming Features Feature Description Encapsulation Mechanism of hiding information from users. For example, the process of dialing a number from your mobile phone involves processes, such as connecting to a mobile service provider and searching for the mobile phone with the number dialed. This information is encapsulated or hidden from you as a user. Abstraction Mechanism by which users are allowed to control the state of an object. For example, the keypad buttons on a mobile phone is an abstraction of the dialing process. Inheritance Mechanism by which a specific class, called a subclass, is derived from a more general class, called a super or base class. For example, WAPenabled mobile phone is a subclass. The general class of all mobile phones. A subclass inherits all the attributes and behaviors of the base class and adds new attributes and behaviors. Polymorphism Mechanism by which a behavior responds differently depending on the object to which it belongs. For example, a common behavior of all mobile phones is to ring. This behavior may differ for individual mobiles.

Advantages of ObjectOriented Programming


The advantages of the objectoriented programming are: Reusing code: Use the same class in several applications. Extending existing applications: Create a part of an application and add it to an existing one.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Creating Classes in Java


To create a class in Java, do the following: 1. Declare the class 2. Define the constructor, if any 3. Define the data members 4. Define the methods

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 }

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

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.

Creating the Data Members


Data members represent the attributes of a class. For example, the Employee class, which represents an employee, can contain data members, such as id and name. The syntax to declare a data member is:
[<access_specifier>][<modifier>]<datatype><var_name>

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.

The optional modifier can be:

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.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

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; }

Creating the Methods


Methods represent the functions performed by a class. For example, the Employee class may contain functions to store and display the employee information, such as ID and name. The syntax to declare a method is:
[<access_specifier>][<modifier>]<return_type><method_name>([argument_list]) { //Code Statements }

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.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

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();

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Creating Classes: An Example


Create a class called Employee, which stores information about employees of an organization. This class contains data members, such as employeeID, employeeName, and employeeAge. The methods of the class contains the methods storeDetails and displayDetails to store and display data. Listing 131 shows the Employee class: Listing 131: The Employee Class
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); } }

To run the Employee class, you need to create an object of the class. Create this object in the main() method.

Creating the main() Method


All Java programs have a main() method. The Java runtime environment invokes the main() method before all other methods of a class. The syntax of this method is:
public static void main (String [] args) { }

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.

Creating an Object of the Class


An object is an instance of a class. You use the new operator to create a class. The syntax to create an object is:
<classname> <objname> = new <constructor>;

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

Java ReferencePoint Suite

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:

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

Figure 131: The Employee Class

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

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:

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

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(); } }

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

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.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Understanding Abstract Classes


Any class that contains one or more abstract methods is an abstract class. You cannot create objects of an abstract class. Any class that derives from an abstract class must override all abstract methods. You can create classes with abstract method if a common method is implemented in different ways in derived classes. For example, all automobiles have certain common behavior, such as rotating wheels and displaying speed. But, if you create a class called automobiles, it will not be able to represent different types of automobiles, such as cars, buses, or trucks. This is because these automobiles implement the behaviors in different ways. To overcome this, you can create a class called Automobiles with abstract methods to represent the behaviors. You can then derive specific subclasses representing each type of automobile and implement the behavior in these subclasses. You declare a class as abstract by using the abstract modifier. The syntax to do is:
abstract class automobile { }

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(); }

Note Remember that abstract methods need to be declared as public.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

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.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

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

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

S-ar putea să vă placă și