25
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 [email protected] Reprinted with permission as a subscription benefit of Books24x7, http://www.books24x7.com/

Designing Java Applications Using Abstract Classes and Interfaces.pdf

Embed Size (px)

Citation preview

Page 1: Designing Java Applications Using Abstract Classes and Interfaces.pdf

All rights reserved. Reproduction and/or distribution in whole or inpart in electronic, paper or other forms without written permission

is prohibited.

Java ReferencePoint SuiteSkillSoft Corporation. (c) 2002. Copying Prohibited.

Reprinted for Balaji Nallathambi, [email protected]

Reprinted with permission as a subscription benefit of Books24x7,http://www.books24x7.com/

Page 2: Designing Java Applications Using Abstract Classes and Interfaces.pdf

Table of Contents Point 18: Designing Java Applications Using Abstract Classes and Interfaces ........................1

Object−Oriented Programming in Java..........................................................................................2 Abstraction and Encapsulation...............................................................................................2 Reusability..............................................................................................................................4 Polymorphism.........................................................................................................................9

Abstract Classes.............................................................................................................................10 Variables and Methods in Abstract Classes.........................................................................10 Extending Abstract Classes and Implementing Interfaces....................................................10 Extending Classes from Abstract Classes............................................................................10 Importance of Abstract Classes............................................................................................11

Interfaces .........................................................................................................................................12 Variables and Methods in Interfaces.....................................................................................12 Extending Interfaces.............................................................................................................12 Implementing Interfaces........................................................................................................12 Blank Interfaces....................................................................................................................13 Importance of Interfaces.......................................................................................................14 Inner Classes........................................................................................................................16

Dynamic Method Lookup in Abstract Classes and Interfaces ...................................................18

Comparing Interfaces and Abstract Classes ...............................................................................21

Related Topics ................................................................................................................................23

i

Page 3: Designing Java Applications Using Abstract Classes and Interfaces.pdf

Point 18: Designing Java Applications UsingAbstract Classes and InterfacesSuchit MalhotraJava is an object−oriented programming (OOP) language similar to C++. Some features of C++ arenot present in Java, such as multiple inheritance and pointers. Java uses interfaces to provide thefunction of multiple inheritances. Java also supports abstract classes, which are used to providecommon behavior in an inheritance hierarchy.

This ReferencePoint discusses the concept of object−oriented programming in Java. It describesabstract classes and interfaces and how to build an application using these concepts. It alsocompares interfaces with abstract classes.

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 4: Designing Java Applications Using Abstract Classes and Interfaces.pdf

Object−Oriented Programming in JavaObject−oriented programming uses the concept of objects. An object is comparable to a real lifeentity. For example, animal, computer, and books are objects. Objects have their own states,behavior, and identity.

Objects can be categorized into classes. A class is a structure from which objects of similarattributes and behavior can be created. A state is the sum total of the values of the properties of anobject. The behavior of an object is the way the object acts in different situations. Identity is theproperty of the object that differentiates it from other objects of the same type.

Objects are created, analyzed, used, and manipulated to perform specific tasks. In object−orientedprogramming, objects cooperate with each other by message passing using predefined methods.You define a structure, which consists of methods and data members. These functions performspecific tasks on data members. The structure is a type that is instantiated to create objects thatinclude both data and functions.

Note The terms object and instance are used interchangeably in an object−oriented programmingparadigm.

There are four principal concepts of object−oriented programming: abstraction, encapsulation,inheritance, and polymorphism.

Abstraction and Encapsulation

Abstraction emphasizes details that are useful to a user, and hides other details. In this way, Javaenables you to write code that provides end users with only the necessary processes to manipulatedata. It also hides complex programming details from the end user.

Although abstraction is often confused with encapsulation, these concepts are complementary toeach other. Encapsulation implements abstraction and packages both attributes and behavior ofsimilar objects in a structure. The data hides itself in the encapsulated structure and is read orwritten only through the member methods of the structure.

Objects communicate with each other using message passing. Objects of different or same classpass messages to each other using public methods of the class. Message passing performs all theoperations in object−oriented programming. An object that sends a message is not concerned withthe data structure of the object that receives the message. This property enables the developmentof independent modules in a big application.

Note Java implements encapsulation using access specifier. Classes cannot access the privatemembers of a class where as public members are accessible from other classes.

Java uses the following access modifiers to make the parent class variables and methods in a childclass available:

public: Makes the variables or methods available to every class, which either makes theinstance of the class or inherits the class.

private: Makes the variables or methods available to only the class members of the currentclass. The other classes, which either inherit from the class or make the object of class, donot have access to private variables. The inherited subclasses can only access the privatemembers of the parent class through the public or protected members of the parent class.

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 5: Designing Java Applications Using Abstract Classes and Interfaces.pdf

protected: Makes the variables or methods available to the subclasses and the classes inthe same package.

Listing 2−18−1 defines a class, Test, with public methods:

Listing 2−18−1: Defining the Test Class

public class Test{ private int x; public Test() { this.x=0; } public void set X (int x) { this.x=x; } public int getX() { return this.x; }}

This code shows that the Test class consists of the data member x, which is encapsulated using theprivate keyword. The public methods are getX() and setX(int x), which return and set the value ofthe private variable x.

Note The this keyword points to the object calling the method.

Listing 2−18−2 defines the UseTest class, which creates objects of the Test class in Listing 2−18−1:

Listing 2−18−2: Defining the UseTest.java Class

public class UseTest{ public static void main(String args[]) { Test obj=new Test(); System.out.println(obj.getX()); obj.setX(5); System.out.println(obj.getX()); }}

In this code, the UseTest class creates the obj object of the Test class in Listing 2−18−1. The objobject calls the methods of the Test class to access and manipulate the value of x, the privatevariable. The obj object uses the getX() and setX() methods to return and set the state of the object,which is the value of the private variable x. The obj object accesses the value of x and the programprints it to the console, as shown in Figure 2−18−1:

Java ReferencePoint Suite 3

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 6: Designing Java Applications Using Abstract Classes and Interfaces.pdf

Figure 2−18−1: Output of the UseTest.java ClassReusability

Reusability refers to using existing classes to simplify the coding of an application. New classes inan application can also use existing classes. The advantage of existing classes is that they havealready been written, tested, and debugged. There are many ways of reusing existing classes inobject−oriented programming, such as association, inheritance, metaclass, aggregation, andinstantiation.

Inheritance

Inheritance is the process in which a class acquires the attributes and behavior of an existing class.Making classes share the common properties of some other classes reduces the overall complexityof the application development process. For example, a vehicle class shares the commonproperties of motorcycle, car, bus, and truck. These vehicles have various properties, such as brandname and engine, which can be included as the attributes of the common Vehicle class.

Inheritance is an important part of object−oriented programming because it reduces the applicationdevelopment process to coding independent modules, which can be written by differentprogrammers and integrated to create the application.

The classes in the inheritance hierarchy are divided into two parts:

Base Class: This is also known as the parent or superclass. It is at the upper level in theinheritance hierarchy of classes. This class is the class from which another class derivesitself. For example, the Vehicle class is the parent class of the Car class.

Derived Class: This is also known as the child class or sub class. It is at a lower level incomparison with some other class of the inheritance hierarchy. This class derives theproperties of the base class. For example, the Car class is the derived class from theVehicle class.

There are various types of Inheritance hierarchy possible in OOP. Some of them include:

Java ReferencePoint Suite 4

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 7: Designing Java Applications Using Abstract Classes and Interfaces.pdf

Single inheritance: Occurs when a derived class inherits from the single base class.•

MultiLevel inheritance: Occurs when a base class of any class is derived from another class.•

Multiple inheritance: Occurs when a derived class inherits from multiple base classes.•

Hierarchical inheritance: Occurs when multiple derived classes have the same base class.•

Note Java supports all types of inheritance except multiple inheritance.

In Java, inheritance is used for two purposes, class inheritance and interface inheritance. Java usesthe extends keyword to inherit the classes from previously written and compiled classes andinterfaces from previously written and compiled interfaces. Java supports multiple inheritance incase of interface inheritance but not in class inheritance.

Note The number of classes in Java is constantly increasing. To avoid running out ofnames for classes, Java uses the concept of a package. A package contains a set ofclasses. The package can be explicitly imported in any class using the importkeyword.

The object class is the superclass for every class written in Java. You do not need to explicitlyextend your classes from the object class. Because every class in Java is a subclass of the objectclass, the instances of the object class can refer to the objects of any class. This property enablesyou to use the objects of the Object class when you need to implement the flexibility of using anyclass in the future. There are many useful methods in the object class, which can be overridden inany class in Java.

Listing 2−18−3 shows how the properties of one class are inherited into another:

Listing 2−18−3: Inheriting the Properties of One Class into Another

class Employee{ public Employee(String name, int age, double pay) { this.name=name; this.age=age; this.pay=pay; } public void show() { System.out.println("Name: "+name); System.out.println("Age: "+age); System.out.println("Pay: "+pay); } public void incrPay(double percent) { this.pay*=1+percent/100; } public void incrPay() { this.pay+=1000; }

public String name; protected int age; private double pay;

Java ReferencePoint Suite 5

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 8: Designing Java Applications Using Abstract Classes and Interfaces.pdf

}

This code contains the Employee class, which contains the member variables name, age, and paywith different access modifiers to get data for any employee. The Employee class contains theshow() method to show the data members in the class, the incrPay(int Percent) method to increasethe value of member variable pay by a specified percent, and the incrPay() method to increase thevalue of pay by 1000.

The Employee class has its own constructor to initialize the values of the member variables of theclass. Each class in Java has a default constructor that does not contain any arguments provided bythe Java run time environment (JRE). If a class does not have a constructor, the default constructoris provided implicitly. If a class has a constructor with parameters, the framework does not providethe default constructor without argument. You need to write the constructor without the argument.Writing different constructors in a class is known as constructor overloading.

The JRE creates the object of the parent class each time the child class is instantiated. If the parentclass does not have a constructor, the implicit default constructor creates the object of the parentclass. When the parent class defines a constructor with an argument, the JRE cannot create aparent class object for the child class. The child class constructor calls the constructor with theargument of the parent class explicitly using the super keyword to create the parent class object.

Listing 2−18−4 shows how to create the Manager class, which inherits from the Employee class ofListing 2−18−3. This code shows how to call the parent class constructor using the super keywordfrom the child class constructor.

Listing 2−18−4: Creating the Manager.java Class

public class Manager extends Employee{ public Manager(String name, int age, double pay, String area) { super(name,age,pay); this.area=area; } public void show() { super.show(); System.out.println("Name of Manager: "+ name); System.out.println("Age of Manager: "+ age); //System.out.println("Pay of Manager: "+ pay); System.out.println("Area of Posting: "+ area); } public static void main(String ar[]) { Manager m1=new Manager("Sam", 24, 3000, "Washington"); m1.show(); m1.incrPay(100); m1.show(); } private String area;}

This code creates the Manager class, which is the subclass of the Employee class in Listing2−18−3. The Manager class inherits the members of the Employee class. The Manager classcontains the area member variable, which cannot be a part of the Employee superclass becausethis attribute is not common to all employees. The Manager class calls the constructor with theargument of Employee class in its constructor and passes the values of name, age, and pay. Thiscreates the Employee class object for the Manager subclass. The constructor also sets the value ofarea with the passed value. If the Manager class constructor does not call the Employee classconstructor explicitly, the JRE cannot create an Employee class object for the Manager class.

Java ReferencePoint Suite 6

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 9: Designing Java Applications Using Abstract Classes and Interfaces.pdf

The show() method of the Manager class overrides the show() method of the parent class. It callsthe show() method of the parent class to display the values of name, age, and pay. It contains thecode to display the values of name, age, and area.

The variable area is the member variable of the Manager class. The Manager class also has accessto the protected variable age and the public variable name of the Employee parent class. Inaddition, the Manager class does not have the access to the pay variable because it is the privatevariable of the Employee parent class. The reference to the pay variable from the Manager classcauses a compile−time error.

The incrPay(int percentage) method is the member of the Employee parent class. It does not haveany definition in the Manager class. The Manager class has the access to this method because it isdeclared as a public member in the parent Employee class. The call to this method refers to theparent class method. Figure 2−18−2 shows the output of the code in Listing 2−18−4:

Figure 2−18−2: Output of the Manager.java classJava supports the usage of the static methods and variables, also known as class methods andclass variables, respectively. Java uses the static keyword to declare a method or a variable asstatic.

Static variables are instantiated only once when a class is loaded in the memory. If you do notexplicitly provide any values in the class, static variables are instantiated with their default values.The default value of the static members differs with their types. For example, the default value forthe integer type static variable is 0.

Static methods are also instantiated when the class is loaded in the memory. Although a staticmethod cannot access the instance members of the class, it can access other static methods andvariables. The class name or any instance of the class can invoke a static method.

Java ReferencePoint Suite 7

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 10: Designing Java Applications Using Abstract Classes and Interfaces.pdf

Note In Java, the main method is always declared as static because it is called by the interpreterbefore instantiating the class.

Java uses the final keyword in the class declaration to prevent the inheritance from a class. Theclasses declared with the final keyword are final classes. Final classes cannot act as the parentclass to any other class. For example, if the Employee class in Listing 2−18−3 is a final class, theinheritance of the Manager class in Listing 2−18−4 from the Employee class is not possible. Finalclasses make programs run faster because they enable the compiler to perform static binding.

Aggregation

Aggregation is a technique to enable code reusability. Although it is a special type of associationamong classes, this relationship may or may not show physical containment among classes. Incontrast to inheritance, the objects in aggregation exist independent of each other. Java implementsaggregation by making the instances of classes in other classes.

Listing 2−18−5 shows how to avoid using inheritance:

Listing 2−18−5: Avoiding the Usage of Inheritance in the Manager.java Class

public class Manager{ public Manager(String name, int age, double pay, String area) { this.emp=new Employee(name,age,pay); this.area=area; } public void show() { emp.show(); System.out.println("Name from Manager: "+ emp.name); //System.out.println("Age from Manager: "+ age); //System.out.println("Pay from Manager: "+ pay); System.out.println("Area of Posting: "+ area); } public static void main(String ar[]) { Manager m1=new Manager("Sam", 24, 15000, "Washington"); m1.show(); m1.emp.incrPay(100); m1.show(); } private String area; private Employee emp;}

In this code, the Manager class makes an object of the Employee class a member variable andinitializes it by passing the necessary values of name, age, and pay variables in the constructor.The super keyword is not used because the Employee class is not a superclass of the Managerclass.

The show() method of Manager class is not related to the Employee class show() method. Thenames of both methods are identical only for symmetry.

In Listing 2−18−4, the Manager class uses the super keyword to call the Employee class show()method, while the Manager class in Listing 2−18−5 doesn't use the super keyword. The empmember variable calls the show() method of the Employee class. In addition to the private variable,pay, the reference to the protected variable, age, is also made a comment because the classesinherited from the specified class can access the protected members of its parent class.

You cannot reference the incrPay(int percent) method directly by the object of the Manager class.The call to the incrPay() method is made through the Employee class object emp.

Java ReferencePoint Suite 8

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 11: Designing Java Applications Using Abstract Classes and Interfaces.pdf

In Listing 2−18−4 and Listing 2−18−5, the Manager class uses the Employee class to show differenttypes of reusability. It is difficult to choose between the design strategies, inheritance andaggregation. One of the main factors that determine the choice is the type of the relation betweenthe classes. Inheritance is used when the 'is−a' relationship is maintained between the classesthroughout the lifetime of objects. Reusability is best achieved through the aggregation withinterface implementation because it makes code debugging and altering easier than inheritance.

Polymorphism

Polymorphism refers to the programming language's ability to use same name for the variable,object, or function. Object−oriented programming supports the use of the same operator andmethod in different ways, depending on the data type with which it is used. Polymorphism isapplicable only when there are two different methods with the same name.

Polymorphism is of two types:

Compile Time: Achieved when the called method is replaced with a memory address atcompile time. Method overloading results in compile time polymorphism. Method overloadingoccurs when the same class contains more than one method with the same name and returntype. The method must differ in the type and number of parameters. For example, in Listing2−18−3, the Employee class contains two different definitions for the incrPay() method. If aclass calls the incrPay() method by passing one double type argument, the value of the payvariable is increased by the percent that is passed as an argument. If the incrPay() methodis called without an argument, the value of the pay variable increases by 1000.

Run Time: Achieved when the run time environment determines the call method by callingthe appropriate method that matches with the object. The run time environment decides themethod call by the object, which is overriding results in run−time polymorphism. Methodoverriding means that a child class in the inheritance hierarchy contains a method with thesame signature as that of the parent class method. The method signature is a combinationof method name, return type, and the type and number of parameters of the methods. Forexample, in Listing 2−18−4, the Manager class overrides the show() method of theEmployee class. Note that the show method of Manager class in Listing 2−18−5 is not anexample of method overriding because the Employee class is not the parent class of theManager class.

Polymorphism also exists in operators. Java provides operator overloading in the built−in classes.For example, the + and = operators work with the String class. The JRE decides the type ofoperator by the type of operands.

Java uses final methods to stop method overriding. The final keyword is used in the methoddefinition of the parent class to stop method overriding by the child class. A method is generallydeclared as final if the method behavior in the class works for the child classes also. Child classesdo not need to change the behavior of the method.

Java ReferencePoint Suite 9

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 12: Designing Java Applications Using Abstract Classes and Interfaces.pdf

Abstract ClassesAn abstract class is a class used as an intermediate between a normal class and an interface. Anabstract class is defined using the abstract keyword. A class with an abstract method must bedeclared abstract. An abstract method does not have a body. The syntax to declare an abstractclass is:

<modifier> abstract class<name> {extends <superclasses>}{implements<superinterfaces> ,.......}{ <method header>{<method body>}........... <variable declaration>...........}

The abstract class cannot be instantiated using the new keyword because the class may or may nothave the method definition for all the methods. The references of the abstract class type can beformed using the child class objects.

By default, the access modifier in an abstract class is public. You cannot use private or protectedmodifiers with abstract classes because they are derived by some class.

Variables and Methods in Abstract Classes

The methods in the abstract class may or may not be abstract, depending on whether or not theyprovide a method definition. You must declare the methods without a body as abstract by using theabstract keyword in the method declaration.

The method ends with a semicolon, similar to a Java statement. You implement abstract methods inthe derived classes. Remember that a derived class that does not implement abstract method mustbe declared abstract.

Note You cannot declare an abstract method as static because it cannot be invoked without animplementation.

The constructor can be defined in abstract classes. It can only be called with the super keyword inthe subclass constructor, which extends the abstract class. These constructors cannot be used tomake the object of abstract class.

You can declare the variables in the abstract class, similar to the simple class. Variables andmethods can be declared as private, protected, final, and static.

Extending Abstract Classes and Implementing Interfaces

An abstract class can inherit a class using the extends keyword. An abstract class can also inheritfrom an abstract class. The abstract class does not need to provide a definition of the methods.

An abstract class can also implement one or more interface without implementing the methods ofinterface. These interface methods, which have not been provided a definition, should be declaredas abstract in the abstract class if the abstract class does not provide the definition of the method.

Extending Classes from Abstract Classes

You must use the abstract class to provide a nonabstract subclass because an abstract classcannot be instantiated. Classes can extend from the abstract classes using the extends keyword.The class extending from the specified abstract class must give a definition to all the abstractmethods. The class can override the nonabstract methods depending on whether or not the defaultimplementation works for the class.

In an inheritance hierarchy of abstract classes, the nonabstract class extending from the lowestabstract class in the hierarchy must provide a definition to each abstract method that has not beenprovided a definition by any class in the hierarchy.

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 13: Designing Java Applications Using Abstract Classes and Interfaces.pdf

Importance of Abstract Classes

The event delegation model defines several listener interfaces to listen to events. It is quite hectic toimplement all the methods of the listener interfaces. In certain situations, not all the eventsassociated with a listener are needed.

Java provides several adapter classes that simplify the creation of event handlers. Adapter classesin Java provide empty implementation for all the methods in the corresponding listener interface.For example, the adapter KeyAdapter class implements the KeyListener listener and providesempty body to the following methods:

void keyPressed(KeyEvent ke)void keyReleased(KeyEvent ke)void keyTyped(KeyEvent ke)

Note The adapter KeyListener class is defined as an abstract class, similar to otheradapter classes, such as MouseAdapter and FocusAdapter.

Listing 2−18−6 shows the sample code to use an adapter class:

Listing 2−18−6: Using an Adapter Class

import Java.awt.event.*;import Java.applet.*;/*<applet code="UseAdapter"width=300 height=100></applet>*/public class UseAdapter extends Applet { public void init() { addKeyListener(new SmallListener(this)); }}class SmallListener extends KeyAdapter{ UseAdapter useAdapter; public SmallListener(UseAdapter useaAapter) { this.useAdapter=useAdapter; } public void keyPressed(KeyEvent ke) { /* necessary implementation using object useAdapter*/ }}

This code contains the UseAdapter and SmallListener classes. In addition, the source and listenerare different classes. The listener class extending from the adapter class makes a handler of thesource class to perform the necessary operations on the corresponding events.

Java ReferencePoint Suite 11

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 14: Designing Java Applications Using Abstract Classes and Interfaces.pdf

InterfacesJava uses interfaces to provide the features of multiple inheritance because classes in Java cannothave more than one superclass. In Java, an interface is a keyword used to define a collection ofmethod definitions and constant values. Interface enables a class to reflect the behavior of morethan one parent class. That is if a class is inheriting from more than one class then it can implementan interface as well.

Note In Java, names of interfaces start with a capital letter and end with the −able or −iblesuffix.

Java uses the keyword interface to define an interface. The syntax to declare an interface is:

<modifier> interface <name> {extends <super interface>,.....}{ <method header>........... <constant declaration>...........}

In this syntax, the modifier can be either public or private. The other access modifiers, protected andprivate, are not used in the interface declaration because a class implements interfaces. This classmust be available to all the classes for implementation. Although the public modifier makes theinterface available to any class, not using the modifier makes the interface available only to thepackage in which the interface is declared.

Interfaces also use the extends keyword to extend from the other interfaces.

Variables and Methods in Interfaces

The variables declared in an interface are implicitly public, final, and static, irrespective of whetheror not they are declared with these keywords.

A final variable is a constant variable and you cannot change its value after it is initialized. Thisvariable acts as the constant class variables for the class that implements the interface.

An interface consists of a method declaration. Interfaces are abstract by nature and are notdeclared using the abstract keyword. The nonabstract class that implements the interface providesthe body to these methods.

Interface methods cannot be native, static, synchronized, final, private, and protected. In addition,the use of the keywords protected, private, transient, volatile, and synchronized with variables isrestricted.

Extending Interfaces

An interface can inherit from other interfaces using the extends keyword. Multiple inheritance is alsopossible because Java enables an interface to inherit the properties of multiple interfaces. Thesyntax to inherit interfaces is the same as that to inherit a class. If an interface extends from multipleinterfaces, a comma separates each parent interface in the declaration of the child interface.

Implementing Interfaces

Classes can use interfaces by implementing them. A class can implement multiple interfaces usingthe implements keyword. A class can specify a number of parent interfaces separated by a commaafter the keyword implements in the class declaration.

A class that implements one or more interfaces must provide a definition to all the methods of theparent interfaces. An abstract class can implement interfaces without giving body to all the methodsof parent interfaces.

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 15: Designing Java Applications Using Abstract Classes and Interfaces.pdf

Blank Interfaces

Blank interfaces are also known as marker interfaces. These interfaces do not contain any body,that is, they do not contain any method or variable. A class can implement a blank interface toprovide additional information about itself. A blank interface tags the classes to show similarbehavior.

Java APIs provide several blank interfaces. For example, cloneable is an important blank interfaceused to make a clone of an object of any class.

The object class in Java consists of the clone() method, which is used to make a bit−wise copy ofthe object. The clone() method is a protected method of the class object. To use the clone methodefficiently in a class, you need to implement the cloneable interface.

Although the default clone method makes a bit−wise copy of the object, you need to override theclone method to clone objects efficiently. You need to do this because the bit−wise copy does notalways work properly. Sometimes, a class contains the object of another class. For example, thecloning of the object of the Employee class in Listing 2−18−3, which uses the default clone()method, works properly because this class consists of default data types.

Listing 2−18−7 shows how to clone the employee class in Listing 2−18−3:

Listing 2−18−7: Cloning the Employee Class

Employee emp1= new Employee("Sam",24,3000);Employee emp2= emp1;Employee emp3= (Employee) emp1.clone();

This code makes an object, emp1, emp2, and emp3, of the employee class. The objects emp1 andemp2 both refer to the same memory location. Any change in either of them changes the otherobject. For example, if the pay of emp1 is incremented using the incrPay(int percent) method of theemployee class, the pay of emp2 will automatically increase by the same percent. The cloned objectemp3 solves this problem by making a bit−wise copy of emp1. Both emp1 and emp3 refer todifferent memory locations. A change in one of them does not affect the other.

Listing 2−18−8 shows how to clone the Manager class, as shown in Listing 2−18−5:

Listing 2−18−8: Cloning the Manager Class

Manager man1= new Manager("Sam", 24, 3000, "Washington");Manager man2= man1.clone();

This code creates clone man2 of the object man1 of the Manager class. This clone displays anincorrect output. The Manager class contains two data members, one of which is an object ofEmployee class. The clone man2 makes a bit−wise copy of the object man1 of the Manager class. Itcopies the corresponding String type area variable, but it only copies the address of the Employeevariable. Both the original object and the clone share the same employee object.

The cloneable interface solves the above problem. For example, both the Employee and Managerclasses can override the clone method by implementing the cloneable interface.

Listing 2−18−9 shows how the changed Employee class supports the cloning of the object of theManager class:

Listing 2−18−9: Cloning the Object of the Employee Class

Public class Employee implements Cloneable{

Java ReferencePoint Suite 13

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 16: Designing Java Applications Using Abstract Classes and Interfaces.pdf

// The code provided in the Listing 2−18−3 public Object clone() { try { //calls the object class clone method return super.clone(); } catch(CloneNotSupportedException _exp) { //this exception does not happen return _exp; } }}

This code contains the implementation of the clone method in the changed Employee class byimplementing the cloneable interface. The clone method in this class calls the default clone methodof the object class because all the member variables of the Employee class are cloneable.

Listing 2−18−10 shows how the changed Manager class can support the cloning of the object of theManager class:

Listing 2−18−10: Cloning the Object of the Manager Class

public class Manager implements Cloneable{ public Object clone() { try { Manager m= (Manager) super.clone(); m.emp= (Employee) emp.clone(); return m; } catch(CloneNotSupportedException _exp) { //this exception does not happen return _exp; } }}

This code contains the changed manager class, which implements the cloneable interface. Themanager class overrides the clone method and does not call the default clone method. The clonemethod in this class makes an object, m, of the manager class using the clone method of the objectclass. The employee variable emp of the object m is cloned again using the clone method that wasoverridden in the employee class. The clone method returns the object m of the manager class. Theclone method separately clones the employee class variable because cloning the manager classobject creates copies of the address pointing to the employee class object.

Importance of Interfaces

The event delegation model in Java defines two parts, source and listeners. When an event occurs,the event source invokes the appropriate method defined in the class that implements thenecessary event listener interfaces. There are several event listener interfaces present in the Javaevent delegation model.

When a listener class implements an event listener interface, it provides body to every methoddefined in the listener interface. For example, if a class implements a KeyListener interface, itdefines the following methods:

void keyPressed(KeyEvent ke)

Java ReferencePoint Suite 14

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 17: Designing Java Applications Using Abstract Classes and Interfaces.pdf

void keyReleased(KeyEvent ke)void keyTyped(KeyEvent ke)

You must register listeners using the addXXXListener(Object obj) methods, which are provided foreach listener interface.

Note XXX is used as a generalized notation for a set of similar words in Java. For example, XXX inaddXXXListener is used as a common notation for Key, Mouse, and Window.

Listing 2−18−11 shows how to use a Listener interface:

Listing 2−18−11: Using Listener Interface

import Java.awt.*;import Java.awt.event.*;import Java.applet.*;/*<applet code="UseListener"width=300 height=100></applet>*/public class UseListener extends Applet implements KeyListener{ public void init() { addKeyListener(this); } public void keyPressed(KeyEvent ke) { // necessary implementation } public void keyReleased(KeyEvent ke) { // necessary implementation } public void keyTyped(KeyEvent ke) { // necessary implementation }}

This code contains the UseListener class, which implements the KeyListener interface and definesall the methods of the interface. The addKeyListener method is used to register the key listener. Theapplet acts as both the source and listener in this example.

Interfaces are used to make callbacks in Java. The callback is a mechanism where a method in oneobject asks a method in another object to notify when an event happens, as shown in Listing2−18−12:

Listing 2−18−12: Implementing Callbacks in Java

interface Inter{ public void show();}class Existing{ Inter inter; Existing(Inter inter) { this.inter=inter; } public void useCall() { inter.show(); } }class CallBack implements Inter

Java ReferencePoint Suite 15

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 18: Designing Java Applications Using Abstract Classes and Interfaces.pdf

{ CallBack() { Existing obj=new Existing(this); } public void show() { System.out.println("show method"); }}

This code defines an interface named inter that calls back the CallBack class, which implementsthis interface. The Existing class makes a reference to Inter interface and uses this reference to callthe show() method. The object of the CallBack class initializes this interface reference. The object ofthe Callback class is passed to the Existing class in the constructor of the CallBack class.

Inner Classes

The inner class is a class that is defined inside another class. The interfaces can also be definedwithin a class definition. The Java compiler handles inner classes. The Java Virtual Machine (JVM)visualizes the inner class as a simple class.

Inner classes can be categorized as nonstatic inner, static inner, or anonymous.

Nonstatic Inner Classes

Nonstatic inner classes can access all the variables and methods, including the private members, ofthe class containing it. The inner classes can refer these private members of the outer class thesame way as they reference their own class members. Nonstatic inner classes are hidden from theother classes in the same package. The object of nonstatic inner classes is created in the context ofan instance of the class enclosing it. A nonstatic inner class can be defined as public, protected,and private.

In Java, you can define local classes that are defined in a block. These classes are completelyhidden from the outside and cannot be accessed even from other parts of the same class outsidethe block.

Static Inner Classes

Static inner classes are made when the inner classes do not need the reference to the outer classobject. These classes are similar to a normal inner class, except that a static inner class is definedusing the static modifier in the class.

Java supports a static interface definition within a class. The classes and interfaces can be nestedto any depth within the top−level class. The interfaces in Java are implicitly static. The static innerclasses and interfaces can be referenced from outside the class. The top−level class or othernested classes can be imported in a program using the import keyword.

Anonymous Classes

Anonymous classes combine the definition and instantiation of a class. These classes do not have aname and are instantiated by returning the object of the parent, which can be a class or aninterface. Listing 2−18−13 shows how anonymous classes are used in Java:

Listing 2−18−13: Using Anonymous Classes

interface ParentI{ public void show(); } class ParentC implements ParentI {

Java ReferencePoint Suite 16

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 19: Designing Java Applications Using Abstract Classes and Interfaces.pdf

public void show() { System.out.println("Parent class show"); }}class UseParent{ public ParentC anonymous1() { return new ParentC() {}; } public ParentC anonymous2() { return new ParentC() { public void show() { System.out.println("Anonymous2 show"); }}; } public ParentI anonymous3() { return new ParentI() { public void show() { System.out.println("Anonymous3 show"); } }; }} public class AnonymousClass { public static void main(String ar[]) { ParentI[] parentI={new UseParent().anonymous1(), new UseParent().anonymous2(), new UseParent().anonymous3() }; for(int i=0; i<parentI.length; i++) parentI[i].show(); }}

The above code consists of an interface, ParentI, and a class, ParentC, which implements theParentI interface. Both act as the parent for the anonymous classes. The UseParent class definesthree methods, anonymous1(), anonymous2(), and anonymous3(), which return the object of thethree new anonymous classes. The anonymous1() method returns an object of the anonymouschild class of the ParentC class, which uses the default show() method of the parent class. Theanonymous2() method returns an object of the anonymous child class of the ParentC class, whichoverrides the show method of the parent class, ParentC. The anonymous3() method returns anobject of the anonymous child class of the interface ParentI. This child class provides a definition forthe show() method of the parent interface.

The AnonymousClass is a public class that defines the main method. The references of the ParentIinterface are created in the main method using all the three methods of the UseParent class.

Java ReferencePoint Suite 17

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 20: Designing Java Applications Using Abstract Classes and Interfaces.pdf

Dynamic Method Lookup in Abstract Classes andInterfacesBinding replaces the methods or attribute names in a program by the actual memory address of themethods and attributes. Binding can be done in the following ways:

Compile Time Binding: Also called static binding. It is the process of replacing the attributenames with their actual values or memory locations at code compilation.

Run Time Binding: Also called dynamic binding. It is the process of replacing the attributeswith the actual values or memory locations while the program is running.

Dynamic method binding is a process in which the run time environment determines the methodcall. This type of binding occurs when there are multiple definitions available for the same method inthe inheritance hierarchy of the class. A class or an interface reference in Java can refer to anyobject in the inheritance hierarchy associated with the class or the interface.

The process of referring an object to any other object in the inheritance hierarchy is known ascasting. There are two types of casting:

Upcasting: Assigns the subclass reference to the superclass reference. Here, the wordsuperclass refers to a class or an abstract class or interface and the subclass is a class thateither extends from the class or implements the interface.

Downcasting: Assigns the superclass reference to the subclass reference.•

In addition to the assignment of the class reference, you can also assign an interface type either toa reference of the object class or to the reference of the parent interface. In addition, you can cast asource array type into an object class reference. You can also cast an array into another array typeif the conversion of a source array type into this array type is possible.

When an object refers to a method, the compiler checks whether or not this method belongs to theclass of that object. If the method is not present in the class, the compiler attempts to find themethod definition in the inheritance hierarchy of the class.

Listing 2−18−14 shows how to implement casting and dynamic method binding:

Listing 2−18−14: Implementing Casting and Dynamic Method Binding

interface TopInter{ public void show();}abstract class Abs{ public abstract void show(); public void show(String s) {System.out.println("Abstract class Abs : "+ s); }}interface Inter extends TopInter{}class Class1 extends Abs implements Inter{ public void show() {

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 21: Designing Java Applications Using Abstract Classes and Interfaces.pdf

System.out.println("Class Class1"); } public void show(String s) { System.out.println("Class Class1 : "+ s); }}class Class11 implements Inter{ public void show() { System.out.println("Class class11"); } public void show(String s) { System.out.println("Class class11 : "+s); }}class Class12 extends Abs{ public void show() { System.out.println("Class class12"); }}class Class2 extends Class1{ public void show() { System.out.println("Class Class2"); } public void show(String s) { System.out.println("Class Class2 : "+s); } }public class Polymorphism{ public static void main(String ar[]) {Inter[] interobj={new Class1(), new Class2(), new Class11()};Abs[] absobj={new Class1(),new Class2(), new Class12()};Class1[] class1obj={new Class1(),new Class2()}; TopInter topinterobj=interobj[0]; for(int i=0;i<interobj.length;i++) { interobj[i].show(); //interobj[i].show("Polymorphism"); } for(int i=0;i<absobj.length;i++) { absobj[i].show(); absobj[i].show("Polymorphism"); } for(int i=0;i<class1obj.length;i++) { class1obj[i].show(); class1obj[i].show("Polymorphism"); } topinterobj.show(); }}

This code defines interfaces, a normal class, an abstract class, and a public class. The TopInterinterface and the Abs abstract class are at the top of the inheritance hierarchy. The TopInterinterface contains the show() method declaration. The Abs abstract class contains the show()method without a parameter and a nonabstract method, show(String s), with the string typeparameter. The TopInter interface and the Abs abstract class are not related.

Java ReferencePoint Suite 19

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 22: Designing Java Applications Using Abstract Classes and Interfaces.pdf

The Inter interface extends from the TopInter interface and does not have any members of its own.The Class1 class extends from the Abs abstract class and implements the interface Inter. This classprovides body to the show() method. The show() method works for both the interface and theabstract class. This class also overrides the show(String s) method of an abstract class.

The Class11 class implements the Inter interface and provides body to the show() method. Thisclass also defines a method, show(String s), of its own. The Class12 class extends from the Absabstract class and provides body to the show() abstract method of the parent class. The Class2class extends from the Class1 class and overrides both the show() and show(String s) methods ofthe Class1 class.

The main method in the public class creates three references of the Inter interface and assigns theobjects of the Class1, Class2, and Class11 classes. The object of the Class12 class cannot beassigned in the interface reference Inter because it does not have any inheritance relation with theinterface.

The three references of the Abs abstract class type are created and the objects of classes Class1,Class2, and Class12 are assigned in them. The two objects of the Class1 class type are instantiatedwith the object of the Class1 and Class2 classes. A reference of the TopInter interface is assignedwith a reference of type Inter, which actually points to the object of the Class1 class.

The show() method is then called with the Inter interface reference. Different show methods arecalled, depending upon the object assigned to the interface reference. The object of the Interinterface cannot visualize the show(String s) method. The show() and show(String s) methods arecalled using the reference of the Abs abstract class and objects of the Class1 class. The TopInterinterface reference calls the show() method.

Note Java files can only contain one public class for each file. In addition, the name of the file andthe public class in Java should not be identical.

Java ReferencePoint Suite 20

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 23: Designing Java Applications Using Abstract Classes and Interfaces.pdf

Comparing Interfaces and Abstract ClassesBoth interfaces and abstract classes are used to write code with a high level of abstraction. Thesimilarity between interfaces and abstract classes is that they cannot be instantiated. This meansthat you can create interfaces and abstract classes only when instantiating them is not necessary.But you can create an object reference to both of them using the child class object.

An interface provides the method declarations for the subclasses to implement. Interfaces are usedto show the common behavior of some of the unrelated classes and declare methods and constantsfor multiple classes.

An abstract class usually provides default behavior for some of the methods and forces anonabstract subclass to implement the remaining abstract methods.

The following are some of the conditions that influence the decision of choosing between interfacesand abstract classes when developing an application:

Use interfaces to make a class extend from another class and inherit its behavior. Forexample, if an applet needs to perform multithreaded operations, it cannot extend from theThread class because it is necessary for an applet to extend from the Java.applet.Appletclass. As a result, an applet has to implement the Runnable interface to show multithreadedbehavior.

Use a regular class to make a parent provide definition for all the methods. In contrast, usean interface if a subclass provides definition to all the methods of a parent class. Anintermediate solution between these two options is an abstract class, where you need toprovide body to some methods and leave other methods as abstract.

Use abstract classes to have any of the private and protected parts, partial implementations,and static parts in the parent in addition to the abstract methods. Interfaces can only havepublic abstract methods and constants.

Use an abstract class if you expect the code of the parent class to change. In this case, theabstract class can provide the partial implementation of the new code. Changes are hard tomake with interfaces because every class based on the interface needs to change also. Forexample, if you need to add a method to an abstract class, the partial implementation can beprovided so that the classes extending from the abstract class need not be changed. If amethod is added to an interface, the method definition must be added in each classimplementing from the interface.

Use abstract classes to have the instance variables in the parent class in addition to theabstract method. This is because the interfaces cannot contain instance variables. Interfacessupport multiple inheritance partially because an interface cannot provide body to anymethod and cannot have variables.

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 24: Designing Java Applications Using Abstract Classes and Interfaces.pdf

Tip Choose interfaces over abstract classes because interfaces do not bind the applicationwith the restrictive inheritance hierarchy of Java. This makes the application easier tomodify, except when you need to add or remove a method in the interface.

Java ReferencePoint Suite 22

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Page 25: Designing Java Applications Using Abstract Classes and Interfaces.pdf

Related TopicsFor related information on this topic, you can refer to:

Understanding Classes and Objects in Java•

Multithreading in Java•

Using Collections in Java•

Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited