Vous êtes sur la page 1sur 154

Chapter Topics

0 OOP

0 Classes and Objects


0 Encapsulation 0 Abstraction 0 Inheritance 0 Polymorphism 0 Abstract class & interfaces 0 Exceptions & Review of Java Fundamentals
Chapter 1 - OOP Principles 2

Object Oriented Programming


0 Object orientation is a set of tools and methods that enable

software engineers to build reliable, user friendly, maintainable, well documented, reusable software systems that fulfills the requirements of its users. 0 Object-orientation provides a new view of computation.
0 A software system is seen as a community of objects that cooperate

with each other by passing messages in solving a problem.

0 At the heart of object-oriented programming, instead of tasks we

find objects entities that:


0 have behaviors, 0 hold information, and

0 can interact with one another.

3
Chapter 1 - OOP Principles

Object Oriented Programming


0 An object-oriented programming language provides support for

the following object-oriented concepts:


0 Objects 0 Classes 0 Inheritance 0 Polymorphism 0 Abstraction

0 Modularity
0 Encapsulation

4
Chapter 1 - OOP Principles

Benefits of OOP 0 The concept of inheritance and the data-oriented approach allow a lot of reuse of existing classes and helps to eliminate redundant code. 0 Programs can be built using working modules that already know how to communicate with each other. This means that programs do not always have to be written from scratch thus saving development time and increasing productivity. 0 Encapsulation (hiding of data) helps with the building of more secure programs as data cannot be unintentionally changed by other parts of the program. 0 There is a close link between objects in the real-world system and objects in the program. Therefore the structure of the system is more likely to be meaningful to users. 0 The work for a project can be divided by class/object making it easier to split work up between a team of developers. 0 OO systems can be easily upgraded from small to larger systems. 0 The message passing technique for communication between objects makes it easy to describe the interface of an OO system for other systems that need to communicate with it. 0 Software complexity can be easily managed.
5
Chapter 1 - OOP Principles

Object Oriented Programming

Class
0 Definition: A class is a blueprint that defines the variables and the 0 0 0 0 0 0

methods common to all objects of a certain kind. A class is a software blueprint for objects. A class is used to manufacture or create objects. The class declares the instance variables necessary to contain the state of every object. The class would also declare and provide implementations for the instance methods necessary to operate on the state of the object. After youve created the class, you can create any number of objects from that class. Parts of the class specify, or describe, what variables and methods the objects will contain. Objects are created and destroyed as the program runs, and there can be many objects with the same structure, if they are created using the same class.
6
Chapter 1 - OOP Principles

0 Declaring a Class

Class

class classname {

datatype instance-variable1;
datatype instance-variable2; // ... datatype instance-variableN; returntype methodname1(parameter-list) { // body of method

} returntype methodname2(parameter-list) { // body of method } // ... returntype methodnameN(parameter-list) { // body of method } } 0 You can also add modifiers like public or private at the very beginning.
7
Chapter 1 - OOP Principles

Class
0 In general, class declarations can include these components, in

order:

0 Modifiers such as public, private, protected, 0 The class name, 0 with the initial letter capitalized by convention. 0 The name of the class's parent (superclass), if any, 0 preceded by the keyword extends. A class can only extend (subclass) one parent. 0 A comma-separated list of interfaces implemented by the class, if

any,

0 preceded by the keyword implements. A class can implement more than

one interface.

0 The class body, surrounded by braces, {}.


8
Chapter 1 - OOP Principles

Class
Access Protection
Variables or Methods with this modifier can be acessed by methods in:

variable or method modifier

Public same class


Classes in same package

Private Protected

No modifier (default)

Y Y Y Y

Y N N N
Chapter 1 - OOP Principles

Y Y Y N

Y Y N N
9

Subclasses
Classes in different packages

0 Example on Declaring a Class

Class

class Rectangle { float height; float width;

float calculateArea(float h, float w) { return (h*w); }

} 0 You can also add modifiers like public or private at the very beginning.
10
Chapter 1 - OOP Principles

First simple Program


1. /* This is a simple Java program. */ 2. class Example { 3. // Your program begins with a call to main(). 4. public static void main(String args[]) { 5. System.out.println(Hello comps!"); 6. } 7. } 0 When the program is run, the following output is displayed: Hello comps!

Chapter 1 - OOP Principles

11

cont
0 Line 1: is multiple line comment which is like in C++.

/*multiple line comment*/ 0 Line 2: class Example { 0 This line uses the keyword class to declare that a new class is being defined. 0 Example is an identifier that is the name of the class. The entire class definition, including all of its members, will be between the opening curly brace ({) and the closing curly brace (}). 0 The use of the curly braces in Java is identical to the way they are used in C, C++, and C#. 0 Line 3: is the single-line comment which is like in C++. // single line comment
Chapter 1 - OOP Principles 12

cont
0 Line 4: public static void main(String args[]) { 0 This line begins the main( ) method. As the comment preceding it

suggests, this is the line at which the program will begin executing. All Java applications begin execution by calling main( ). (This is just like C/C++.) 0 The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. (The opposite of public is private, which prevents a member from being used by code defined outside of its class.) 0 In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program is started.
Chapter 1 - OOP Principles 13

cont
0 The keyword static allows main( ) to be called without having to

instantiate a particular instance of the class. This is necessary since main( ) is called by the Java interpreter before any objects are made. 0 The keyword void simply tells the compiler that main() does not return a value. 0 In main( ), there is only one parameter, albeit a complicated one. String args[ ] declares a parameter named args, which is an array of instances of the class String. (Arrays are collections of similar objects.) Objects of type String store character strings. 0 In this case, args receives any command-line arguments present when the program is executed.

Chapter 1 - OOP Principles

14

0 Line:5

cont

System.out.println(Hello Comps!"); 0 This line outputs the string Hello Comps! followed by a new line on the screen. 0 Output is actually accomplished by the built-in println() method. In this case, println( ) displays the string which is passed to it. 0 As you will see, println( ) can be used to display other types of information, too. 0 The line begins with System.out. - System is a predefined class that provides access to the system, and out is the output stream that is connected to the console

Chapter 1 - OOP Principles

15

6.Structure of a Class
0 All Java code is written inside classes. 0 The class definition is the first part of the code that appears. This

consists of the access modifier for the class (public or private), the class keyword and the name of the class. 0 By convention, class names begin with an upper case letter.For example, to define a class called Circle :
public class Circle { }

Chapter 1 - OOP Principles

16

cont
0 Inside the class, the code can be divided into fields, constructors

and methods. 0 The fields are the data members of the class. The data members can be class variables or instance variables. 0 The constructors are special methods that are called when an object is instantiated from the class. There can be more than one constructor for a class as long as each constructor has a different parameter list. For example, in a Circle class, the radius for a new object could be passed to the constructor, or if no radius is passed, a default value could be assigned for the radius. In fact, this also applies to methods. This feature of Java is called method overloading.

Chapter 1 - OOP Principles

17

cont
0 The methods implement the behaviour of the objects belonging to

the class. Generally, methods return information about the state of an object or they change the state of an object. These are sometimes called accessor and mutator methods. 0 The order of these parts of a class is generally not important, but placing the fields and then the constructors at the beginning does make the class readable and easy to get around for programmers. Of course, comment blocks should also be used to document the code.

Chapter 1 - OOP Principles

18

public class Circle {


//data private double radius; //constructors public void Circle () { radius = 1.0;}

cont (Eg)

public void Circle (double r) { radius = r; }

//methods public double calcArea() { return 3.14* radius * radius; }


public void draw() { }

Chapter 1 - OOP Principles

19

Defining Methods
0 To declare method:

modifier returntype nameOfMethod(parrameterlist) { //body of the method }


0 The only required elements of a method declaration are the

method's return type, name, a pair of parentheses, ( ), and a body between braces, {}. 0 Note: Parameters refers to the list of variables in a method declaration. 0 Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.
Chapter 1 - OOP Principles 20

Defining Methods(cont)
0 More generally, method declarations have six components, in

order:

0 Modifierssuch as public, private, and others. 0 The return typethe data type of the value returned by the method,

or void if the method does not return a value. 0 The method name 0 The parameter list in parenthesisa comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, ().

0 If there are no parameters, you must use empty parentheses.


0 An exception list 0 The method body, enclosed between braces

0 Definition: Two of the components of a method declaration

comprise the method signaturethe method's name and the parameter types.
Chapter 1 - OOP Principles

21

0 Although a method name can be any legal identifier, code

Defining Methods(cont) Naming a Method

conventions restrict method names. 0 By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc.
0 In multi-word names, the first letter of each of the second and

following words should be capitalized.

Chapter 1 - OOP Principles

22

Defining Methods(cont) Overloading Methods


0 Overloading is when the same method or operator can be

used on many different types of data. 0 The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures.
0 This means that methods within a class can have the same

name if they have different parameter lists

0 Java does not support operator overloading.

Chapter 1 - OOP Principles

23

Defining Methods(cont) Overloading Methods(cont)


0 Overloaded methods are differentiated by the number

and the type of the arguments passed into the method. 0 You cannot declare more than one method with the same name and the same number and type of arguments 0 fThe compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.
Chapter 1 - OOP Principles

24

Defining Methods(cont) Overloading Methods(cont)


0 Example on Overloading methods

class Rectangle { float height, width; float calculateArea(float h, float w) { return (h*w); } float calculateArea(int h, float w){ return (h*w); } float calculateArea(float h, int w){ return (h*w); } int calculateArea(int h, int w){ return (h*w); } int calculateArea(int h){ return (h*h); } int calculateArea(){ return (0); Chapter 1 - OOP Principles } }

25

Objects
0 Definition: An object is a software bundle of variables and

related methods. 0 In OOP we create software objects that model real world objects. 0 Software objects are modeled after real-world objects in that they have state and behavior.
0 A software object maintains its state in one or more variables. A

variable is an item of data named by an identifier. 0 A software object implements its behavior with methods. A method is a function associated with an object.

0 An object is also known as an instance. An instance refers to a

particular object. 0 The variables of an object are formally known as instance variables because they contain the state for a particular object or instance.
26
Chapter 1 - OOP Principles

0 An object stores its state in fields (variables in some programming languages) and exposes behavior through methods (functions in some programming languages). 0 Bundling code into individual software objects provides a number of

Objects

benefits, including:

0 Modularity: The source code for an object can be written and maintained

independently of the source code for other objects. 0 Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world. 0 Code re-use: If an object already exists you can use that object in your program. This allows specialists to implement/test/debug complex, taskspecific objects. 0 Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a 27 different object as its replacement.
Chapter 1 - OOP Principles

Question: If an object is also a collection of variables and methods, how do they differ from classes?
Answer: No memory is allocated when a class is created. Memory allocation happens only when the actual instances of a class(the objects) are created.

Chapter 1 - OOP Principles

28

Creating Objects
0 A class provides the blueprint for objects; you create an object

from a class. 0 Creating objects has three part:

0 Declaration: associate a variable name with an object type. 0 Instantiation: The new keyword is a Java operator that creates the

object. 0 Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

Chapter 1 - OOP Principles

29

Creating Objects(cont)
0 Declaring a Variable to Refer to an Object

1.Declaration

type name;
0 This notifies the compiler that you will use name to refer to data

whose type is type. 0 With a primitive variable, this declaration also reserves the proper amount of memory for the variable.

0 Simply declaring a reference variable does not create an object. For that, you need to use the new operator.

0 A variable in this state, which currently references no object

e.g., Rectangle Rec1;


Chapter 1 - OOP Principles 30

Creating Objects(cont)
2. Instantiating a Class
0 The new operator instantiates a class by allocating memory for a

new object and returning a reference to that memory. 0 The new operator also invokes the object constructor. 0 The new operator requires a single, postfix argument: a call to a constructor. 0 The name of the constructor provides the name of the class to instantiate. 0 Reference is usually assigned to a variable of the appropriate type, like:

Rectangle Rec1; //declaration Rec1= new Rectangle (); Intantiation


Chapter 1 - OOP Principles 31

Creating Objects(cont)
2. Instantiating a Class(cont)
0 Eg.

Line 1 : Rectangle Rec1; Line 2 : Rectangle Rec1 = new Rectangle (); 0 The first line declares Rec1 as a reference to an object of type Rectangle . After this line executes, Rec1 contains the value null, which indicates that it does not yet point to an actual object. Any attempt to use Rec1 at this point will result in a compile-time error. 0 The second line allocates an actual object and assigns a reference to it to Rec1 . After the second line executes, you can use Rec1 as if it were a Rectangle object. But in reality, Rec1 simply holds the memory address of the actual Rectangle object.
Chapter 1 - OOP Principles 32

0 Here's the code for the Rectangle class:

Creating Objects(cont) 3. Initializing an Object

class Rectangle { float height = 1, width =1; float calculateArea(float h, float w) { return (h*w); } // constructor public Rectangle(float h, float w){ height = h; width = w; } }
0 The following statement provides 2 and 4 as values for those arguments:

Rectangle Rec1= new Rectangle (2,4); // this will initialize the members of Rec1, i.e Rec1.height to be 2 and Rec1.width to 4.
Chapter 1 - OOP Principles 33

Referencing an Object's Fields


0 Object fields are accessed by their name. You must

use a name that is unambiguous. 0 You may use a simple name for a field within its own class. 0 Code that is outside the object's class must use an object reference or expression, as in: objectReference.fieldName; 0 Objects of the same type have their own copy of the same instance fields.
Chapter 1 - OOP Principles 34

Object referencing
0 When you access an instance field through an object

reference, you are referencing the particular object's field. 0 To access a field, you can use a named reference to an object, or you can use any expression that returns an object reference. 0 Recall that the new operator returns a reference to an object.

int height = new Rectangle().height;


Chapter 1 - OOP Principles 35

Calling an Object's Methods


0 Once you've created an object, you probably want to use it for

something. 0 You may need to use the value of one of its fields, change one of its fields, or call one of its methods to perform an action. 0 You also use an object reference to invoke an object's method. 0 You append the method's simple name to the object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.

objectReference.methodName(argumentList); orobjectReference.methodName();
Chapter 1 - OOP Principles 36

Constructors
0 A constructor creates a new instance of the class. 0 It initializes all the variables and does any work

necessary to prepare the class to be used. 0 A constructor has the same name as the class. 0 If no constructor exists Java provides a generic one that takes no arguments which is called the default constructor. 0 You make a constructor by writing a method that has the same name as the class.

Chapter 1 - OOP Principles

37

Constructors(cont)
0 Constructors do not have return types. 0 They do return an instance of their own class, but this is implicit(hidden), not explicit. 0 Example:

// constructors Rectangle(){ // editing the default constructor height = 1; width = 1; } Rectangle(float height, float width){ // parametrized constructor this.height = height; this.width = width; } Chapter 1 - OOP Principles 38

Constructors(cont) class Rectangle {


0 Example:

float height; float width;

float calculateArea(float h, float w) { return (h*w); }


// constructors Rectangle(){ // editing the default constructor height = 1; width = 1; } Rectangle(float height, float width){ // parametrized constructor this.height = height; this.width = width; } Chapter 1 - OOP Principles 39

Constructors(cont)
0 In the above eg, weve used a keyword this
Rectangle(float height, float width){ // parametrized constructor this.height = height; this.width = width; } 0 Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. 0 this can be used inside any method to refer to the current object. 0 That is, this is always a reference to the object on which the method was invoked. You can use this anywhere a reference to an object of the current class type is permitted.
Chapter 1 - OOP Principles 40

0 You can use any data type for a parameter of a method or a

Constructors(cont) Parameter Types

constructor.

0 This includes primitive data types, such as doubles, floats, and

integers, and reference data types, such as objects and arrays. Eg: Eg.1: public Polygon polygonFrom(Rectangle[] recs) { // method body goes here } Eg.2: public int Something(int[] x) { // // method body goes here }

0 Note: The Java programming language doesn't let you

pass methods into methods. But you can pass an object into a method and then invoke the object's methods. Chapter 1 - OOP Principles 41

Constructors(cont) Arbitrary Number of Arguments


0 You can use a construct called var args to pass an

arbitrary number of values to a method. 0 To use var args, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. 0 The method can then be called with any number of that parameter, including none.
0 The method can be called either with an array or with a

sequence of arguments. The code in the method body will treat the parameter as an array in either case.
Chapter 1 - OOP Principles

42

Constructors(cont) Arbitrary Number of Arguments(cont)


public int calculateArea(Rectangle... recs) { recs[0].height = 4; recs[0].width = 5; return (calculate(recs[0].calculateArea(1,2))); } Let say we have an object called Rec1, And you can call this method like this: int result = Rec1.calculateArea(Rec1);
Chapter 1 - OOP Principles 43

Constructors(cont) Parameter Names


0 The name of a parameter must be unique in its scope. 0 It cannot be the same as the name of another parameter for the same method or constructor, and it cannot be the name of a local variable within the method or constructor. 0 A parameter can have the same name as one of the class's fields. 0 If this is the case, the parameter is said to shadow the field. 0 For example, consider the following Circle class and its setOrigin

method: public class Circle { private int x, y, radius; public void setOrigin(int x, int y) { ... } Chapter 1 - OOP Principles }

44

Constructors(cont) Passing Primitive Data Type Arguments


0 Primitive arguments, such as an int or a double, are

passed into methods by value.

0 This means that any changes to the values of the

parameters exist only within the scope of the method. 0 When the method returns, the parameters are gone and any changes to them are lost.

Chapter 1 - OOP Principles

45

Constructors(cont) Passing Reference Data Type Arguments


0 Reference data type parameters, such as objects, are

also passed into methods by value.

0 This means that when the method returns, the passed-in

reference still references the same object as before. 0 However, the values of the object's fields can be changed in the method, if they have the proper access level.

Chapter 1 - OOP Principles

46

Example:

class Rectangle { float height; float width;

class MethodsAndConstructors{ public static void main(String[] args){ Rectangle R1=new Rectangle(); System.out.println(R1-height+R1. height + float calculateArea() { R1-width + R1.widht); return (height*width); System.out.println(R1} public changeValue(Rectangle[] rec){ Area+R1.calculateArea()); rec[0].height = 2; R1.changeValue(R1) ; rec[0].width = 2; System.out.println(R1-height+R1. height + } public changeValueByVar(Rectangle recs){ R1-width + R1.widht); recs[0].height = 4; System.out.println(R1rec[s0].width = 4; Area+R1.calculateArea()); } Rectangle R2=new Rectangle(5,3); // constructors System.out.println(R2-height+R2. height + Rectangle(){ // editing the default constructor R2-width + R2.widht); height = 1; System.out.println(R2width = 1; Area+R2.calculateArea()); } Rectangle(float height, float width){ // R2.changeValueByVar(R1) ; parametrized constructor System.out.println(R1-height+R1. height + this.height = height; R1-width + R1.widht); this.width = width; } System.out.println(R1} Area+R1.calculateArea()); } Chapter 47 } 1 - OOP Principles

Using the this keyword


0 Within an instance method or a constructor, this is a reference to the current

object the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. Using this with a Field 0 The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter. 0 For example, the Point class was written like this public class Point { public int x = 0; public int y = 0; //constructor public Point(int a, int b) { x = a; y = b; } } Chapter 1 - OOP Principles 48

Using the this keyword(cont)


0 but it could have been written like this: 0 public class Point {

public int x = 0; public int y = 0; //constructor public Point(int x, int y) { this.x = x; this.y = y; } } 0 Each argument to the constructor shadows one of the object's fields inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.
Chapter 1 - OOP Principles 49

Using this with a Constructor 0 From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. public class Rectangle { private int x, y; private int width, height; public Rectangle() { this(0, 0, 0, 0); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } ... Chapter 1 - OOP Principles 50 }

Using the this keyword(cont)

Using the this keyword(cont)


0 This class contains a set of constructors. Each constructor

initializes some or all of the rectangle's member variables. 0 The constructors provide a default value for any member variable whose initial value is not provided by an argument. 0 For example, the no-argument constructor calls the four-argument constructor with four 0 values and the two-argument constructor calls the four-argument constructor with two 0 values. 0 As before, the compiler determines which constructor to call, based on the number and the type of arguments. 0 If present, the invocation of another constructor must be the first line in the constructor.

Chapter 1 - OOP Principles

51

Encapsulation

Encapsulation is the hiding of data implementation by restricting access to accessors and mutators. Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. Accessor : is a method that is used to ask an object about itself. Accessor methods are any public method that gives information about the state of the object. Mutator : are public methods that are used to modify the state of an object, while hiding the implementation of exactly how the data gets modified.
52
Chapter 1 - OOP Principles

Encapsulation
Class Person{ private String fullName; public String setFullName(String _fullName){ fullName = _fullName; } public String getFullName(){ return fullName; } } So, the use of mutators and accessors provides many advantages. By hiding the implementation of our Person class, we can make changes to the Person class without the worry that we are going to break other code that is using and calling the Person class for information. This type of data protection and implementation protection is called Encapsulation. 53
Chapter 1 - OOP Principles

The Garbage Collector


0 Some object-oriented languages require that you keep track of all the

objects you create and that you explicitly destroy them when they are no longer needed. 0 Managing memory explicitly is tedious and error-prone. 0 The Java platform allows you to create as many objects as you want (limited, of course, by what your system can handle), and you don't have to worry about destroying them. 0 The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection.

Chapter 1 - OOP Principles

54

The Garbage Collector(cont)


0 An object is eligible for garbage collection when there are no

more references to that object. 0 References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null. 0 Remember that a program can have multiple references to the same object; all references to an object must be dropped before the object is eligible for garbage collection. 0 The Java runtime environment has a garbage collector that periodically frees the memory used by objects that are no longer referenced. The garbage collector does its job automatically when it determines that the time is right.
Chapter 1 - OOP Principles 55

Nested Classes
0 The Java programming language allows you to define a class

within another class. Such a class is called a nested class and is illustrated here: class OuterClass { ... class NestedClass { ... } } 0 Nested classes are divided into two categories: static and nonstatic. 0 Nested classes that are declared static are simply called static nested classes. 0 Non-static nested classes are called inner classes.
Chapter 1 - OOP Principles 56

Nested Classes(cont)
class OuterClass {

... static class StaticNestedClass { ...

}
class InnerClass { ... }
}

0 A nested class is a member of its enclosing class. 0 Non-static nested classes (inner classes) have access to other

members of the enclosing class, even if they are declared private. 0 Static nested classes do not have access to other members of the enclosing class. 0 As a member of the OuterClass, a nested class can be declared private, public, protected,Chapter or package private. 1 - OOP Principles 57

Nested Classes(cont) Static Nested Classes


0 A static nested class is associated with its outer class.

0 And like static class methods, a static nested class cannot refer

directly to instance variables or methods defined in its enclosing class it can use them only through an object reference. 0 Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

Chapter 1 - OOP Principles

58

Nested Classes(cont) Static Nested Classes(cont)


0 Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass
0 For example, to create an object for the static nested class, use this

syntax:

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Chapter 1 - OOP Principles

59

Nested Classes(cont) Inner Classes


0 As with instance methods and variables, an inner class is

associated with an instance of its enclosing class and has direct access to that object's methods and fields. 0 Also, because an inner class is associated with an instance, it cannot define any static members itself. 0 Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass { ... class InnerClass { ... } } Chapter 1 - OOP Principles

60

Nested Classes(cont) Inner Classes(cont)


0 An instance of InnerClass can exist only within an instance of

OuterClass and has direct access to the methods and fields of its enclosing instance. 0 To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Chapter 1 - OOP Principles

61

Nested Classes(cont) Inner Classes(cont) Local and Anonymous Inner Classes


0 There are two additional types of inner classes. 0 You can declare an inner class within the body of a method. Such a class is known as a local inner class. 0 You can also declare an inner class within the body of a method without naming it. These classes are known as anonymous inner classes. 0 You will encounter such classes in advanced Java programming.

Chapter 1 - OOP Principles

62

Nested Classes(cont) Types of nested classes


Types of Nested Classes Type static nested class inner [non-static] class Scope member member Inner no yes

local class
anonymous class

local
only the point where it is defined
Chapter 1 - OOP Principles

yes
yes
63

Nested Classes(cont)
Why Use Nested Classes?
0 There are several compelling reasons for using nested

classes, among them:

0 It is a way of logically grouping classes that are only

used in one place. 0 It increases encapsulation. 0 Nested classes can lead to more readable and maintainable code.

Chapter 1 - OOP Principles

64

Nested Classes(cont) Why Use Nested Classes?(cont)


0 Logical grouping of classesIf a class is useful to only one other

class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined. 0 Increased encapsulationConsider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world. 0 More readable, maintainable codeNesting small classes within top-level classes places the code closer to where it is used.

Chapter 1 - OOP Principles

65

The 4 basic Principles of OOP at a Glance


0 The 4 major principles that make a

language object-oriented: 0 Encapsulation 0 Data Abstraction 0 Polymorphism 0 Inheritance.

Chapter 1 - OOP Principles

66

The 4 basic Principles of OOP at a Glance(ct)


1.

Encapsulation Encapsulation is the hiding of data implementation by restricting access to accessors and mutators. Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. Accessor : is a method that is used to ask an object about itself. Accessor methods are any public method that gives information about the state of the object. Mutator : are public methods that are used to modify the state of an object, while hiding the implementation of exactly how the data gets modified.
Chapter 1 - OOP Principles 67

The 4 basic Principles of OOP at a Glance(ct)


Encapsulation (cont) Class Person{ private String fullName = Abe Gubegna; public String setFullName(String _fullName){ fullName = _fullName; } public String getFullName(){ return fullName; } } So, the use of mutators and accessors provides many advantages. By hiding the implementation of our Person class, we can make changes to the Person class without the worry that we are going to break other code that is using and calling the Person class for information. This type of data protection and implementation protection is called 68 Encapsulation. Chapter 1 - OOP Principles
1.

The 4 basic Principles of OOP at a Glance(ct)


2. Abstraction 0 Data abstraction : is the development of classes, objects, types in terms of their interfaces and functionality, instead of their implementation details. 0 Abstraction denotes a model, a view, or some other focused representation for an actual item. Its the development of a software object to represent an object we can find in the real world. Encapsulation hides the details of that implementation. 0 Abstraction is used to manage complexity. Software developers use abstraction to decompose complex systems into smaller components. 0 An abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of object and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer. G. Booch, Object-Oriented Design With Applications, Benjamin/Cummings, Menlo Park, California, 1991. 0 In short, data abstraction is nothing more than the implementation of an object that contains the same essential properties and actions we can find in the original object we are representing.
Chapter 1 - OOP Principles 69

The 4 basic Principles of OOP at a Glance(ct)


3. Inheritance 0 Objects can relate to each other with either a has a, uses a or an is a relationship. 0 Is a is the inheritance way of object relationship. So, take a library, for example. A library lends more than just books, it also lends magazines, audiocassettes and microfilm. On some level, all of these items can be treated the same: All four types represent assets of the library that can be loaned out to people. However, even though the 4 types can be viewed as the same, they are not identical. A book has an ISBN and a magazine does not. And audiocassette has a play length and microfilm cannot be checked out overnight. 0 Each of these librarys assets should be represented by its own class definition. Without inheritance though, each class must independently implement the characteristics that are common to all loanable assets. All assets are either checked out or available for checkout. All assets have a title, a date of acquisition and a replacement cost. 0 Therefore rather than duplicating functionality, inheritance allows you to inherit functionality from another class, called a superclass or base class.
Chapter 1 - OOP Principles 70

The 4 basic Principles of OOP at a Glance(ct)


4. Polymorphism 0 Polymorphism means one name, many forms. 0 Polymorphism manifests itself by having multiple methods all with the same name, but slightly different functionality. 0 There are 2 basic types of polymorphism, overriding and overloading. 0 Overloading also called compile-time polymorphism : for method overloading, the compiler determines which method will be executed, and this decision is made when the code gets compiled. 0 Overriding also called run-time polymorphism : Which method will be used for method overriding is determined at runtime based on the dynamic type of an object.
Chapter 1 - OOP Principles 71

1. Inheritance
0 The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some

0
0 0

0
0 0

of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself. OOP allows classes to inherit commonly used state and behavior from other classes. Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass and adds its own, unique elements. In Java, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses. A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. 72

1. Inheritance(cont)
0 The syntax for creating a subclass, use the extends keyword,

followed by the name of the class to inherit from: class SuperClassName{ //fields and methods of the super class } class SubClassName extends SuperClassName{ // new fields and methods other than super class }

Chapter 1 - OOP Principles

73

1. Inheritance(cont)
0 Subclass: A class that is derived from another class. Also called a

derived class, extended class, or child class 0 Superclass: The class from which the subclass is derived. Also a base class or a parent class. 0 Except Object, which has no superclass, every class has one and only one direct superclass (single inheritance).
0 In the absence of any other explicit superclass, every class is

implicitly a subclass of Object.

0 Classes can be derived from classes that are derived from classes,

and so on, and ultimately derived from the topmost class, Object.

Chapter 1 - OOP Principles

74

1. Inheritance(cont)
0 The Object class, defined in the java.lang package, defines and

implements behavior common to all classesincluding the ones that you write. 0 In the Java platform, many classes derive directly from Object, other classes derive from some of those classes, and so on, forming a hierarchy of classes. 0 At the top of the hierarchy, Object is the most general of all classes. Classes near the bottom of the hierarchy provide more specialized behavior

Chapter 1 - OOP Principles

75

class SimpleInheritance { public static void main(String args[]) { Example : A superOb = new A(); B subOb = new B(); // Create a superclass. // The superclass may be used by itself. class A { superOb.i = 10; int i, j; superOb.j = 20; void showij() { System.out.println("superOb Contents :"); System.out.println("i and j: "+ i + " "+j); superOb.showij(); System.out.println(); } /* The subclass has access to all public } members of its superclass. */ // Create a subclass by extending class A. subOb.i = 7; class B extends A { subOb.j = 8; subOb.k = 9; int k; System.out.println(subOb Contents : "); void showk() { subOb.showij(); System.out.println("k: " + k); subOb.showk(); } System.out.println(); void sum() { System.out.println("Sum of i, j and k in subOb:"); System.out.println("i+j+k: " + (i+j+k)); subOb.sum(); } } } Chapter 1 - OOP Principles 76 }

1. Inheritance(cont)

0 The output from this program is shown here:


Contents of superOb: i and j: 10 20 Contents of subOb: i and j: 7 8 k: 9 Sum of i, j and k in subOb: i+j+k: 24

1. Inheritance(cont)

0 As you can see, the subclass B includes all of the members of its

superclass, A. This is why subOb can access i and j and call showij( ). Also, inside sum( ), i and j can be referred to directly, as if they were part of B. 0 Even though A is a superclass for B, it is also a completely independent, stand-alone class. Being a superclass for a subclass does not mean that the superclass cannot be used by itself. Further, a subclass can be a superclass for another subclass. 0 You can only specify one superclass for any subclass that you create. Java does not support the inheritance of multiple superclasses into a single subclass. (This differs from C++, in which you can inherit multiple base classes.) You can, as stated, create a hierarchy of inheritance in which a subclass becomes a superclass of1another subclass. However, no class Chapter - OOP Principles 77 can be a superclass of itself.

0 Although a subclass includes all of

1. Inheritance(cont)

// A's j is not accessible here. the members of its superclass, it class B extends A { cannot access those members of int total; the superclass that have been void sum() { declared as private. For example, total = i + j; consider the following simple // ERROR, j is not accessible here class hierarchy: } Example : } // Create a superclass. class Access { public static void main(String args[]){ class A { B subOb = new B(); int i; // public by default subOb.setij(10, 12); private int j; // private to A subOb.sum(); void setij(int x, int y) { System.out.println("Total is " + subOb.total); i = x; } j = y; } } Chapter 1 - OOP Principles 78 }

1. Inheritance(cont)
0 This program will not compile because the reference to j inside

the sum( ) method of B causes an access violation. Since j is declared as private, it is only accessible by other members of its own class. Subclasses have no access to it. 0 A class member that has been declared as private will remain private to its class. It is not accessible by any code outside its class, including subclasses.

Chapter 1 - OOP Principles

79

0 Example :

1. Inheritance(cont)

class Circle{ double radius; // construct clone of an object Circle(Circle cir){ // pass object to constructor radius = cir.radius; } // constructor used when radius is specified Circle(double rad){ radius = rad; } // constructor used when radius is not specified Circle(){ radius = 0.0; }

void displayAreaOfCircle(){ System.out.println("Area of the circle is:" + (Math.PI * radius * radius)); }


Chapter 1 - OOP Principles 80

1. Inheritance(cont) class Cylinder extends Circle{

double height; //constructor for Cylinder Cylinder(double rad, double hei){ radius = rad; height = hei; } void displayAreaOfCylinder(){ System.out.println("Area of the cylinder is:" + (Math.PI * radius * radius * height)); }

public class test { public static void main(String[] args) { Cylinder cyl = new Cylinder(2, 4); System.out.println("Super Class Method call : " ); cyl. displayAreaOfCircle(); System.out.println("Sub Class Method call :" ); cyl. displayAreaOfCylinder();

Chapter 1 - OOP Principles

81

1. Inheritance(cont)
0 A reference variable of a superclass can be assigned a reference to

A Superclass Variable Can Reference a Subclass Object

any subclass derived from that superclass. You will find this aspect of inheritance quite useful in a variety of situations. For example, consider the following:

class SubClassExample { public static void main(String args[]) { Cyliner cyl = new Cylinder(2, 4); Circle cir = new Circle(); System.out.println(Sub Class Method call :); cyl. displayAreaOfCylinder()); // assign Cylinder reference to Circle reference cir = cyl; System.out.println(Super Class Method call :" ); cyl. displayAreaOfCircle()); // cir.height; //is invalid because cir doesnt define the height. Chapter 1 - OOP Principles }}

82

0 In the preceding examples, classes derived from Circle were not 0

1. Inheritance(cont) Using super

implemented as efficiently or as robustly as they could have been. For example, the constructor for cyl explicitly initializes the radius field of Circle( ). Not only does this duplicate code found in its superclass, which is inefficient, but it implies that a subclass must be granted access to these members. However, there will be times when you will want to create a superclass that keeps the details of its implementation to itself (that is, that keeps its data members private). In this case, there would be no way for a subclass to directly access or initialize these variables on its own. Since encapsulation is a primary attribute of OOP, it is not surprising that Java provides a solution to this problem. Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super. super has two general forms. The first calls the superclass constructor. The second is used to access a member of the superclass that has83 been Chapter 1 - OOP Principles hidden by a member of a subclass.

1. Inheritance(cont)
0 A subclass can call a constructor method defined by its superclass

Using super-Use 1(cont)

by use of the following form of super: super(parameter-list); 0 Here, parameter-list specifies any parameters needed by the constructor in the superclass. super( ) must always be the first statement executed inside a subclass constructor. 0 To see how super() is used, consider this improved version of the Cylinder( ) class:

public class Cylinder extends Circle{ double height; //constructor for Cylinder which initialize radius using super() Cylinder(double rad, double hei){ super(rad); // call to super class constructor height = hei; } void displayAreaOfCylinder(){ System.out.println(Area of the cylinder is: + (Math.PI * r * r * h)); } Chapter 1 - OOP Principles 84 }

1. Inheritance(cont)
Using super-Use 2(cont)
0 The second form of super acts somewhat like this, except that it

always refers to the superclass of the subclass in which it is used. This usage has the following general form: super.member 0 Here, member can be either a method or an instance variable. 0 This second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass. Consider this simple class hierarchy:

Chapter 1 - OOP Principles

85

1. Inheritance(cont)
Using super-Use 2(cont)
// Using super to overcome name hiding. class A { int i; } // Create a subclass by extending class A. class B extends A { int i; // this i hides the i in A B(int a, int b) { super.i = a; // i in A i = b; // i in B } void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); } } class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } Chapter 1 - OOP Principles }

86

Creating a Multilevel Hierarchy


0 Up to this point, we have been using simple class hierarchies that

1. Inheritance(cont)

consist of only a superclass and a subclass. However, you can build hierarchies that contain as many layers of inheritance as you like. 0 It is perfectly acceptable to use a subclass as a superclass of another. For example, given three classes called A, B, and C, C can be a subclass of B, which is a subclass of A. 0 When this type of situation occurs, each subclass inherits all of the traits found in all of its superclasses. In this case, C inherits all aspects of B and A.

Chapter 1 - OOP Principles

87

1. Inheritance(cont)

When Constructors Are Called

0 When a class hierarchy is created, in what order are the

constructors for the classes that make up the hierarchy called? 0 For example, given a subclass called B and a superclass called A, is As constructor called before Bs, or vice versa? 0 The answer is that in a class hierarchy, constructors are called in order of derivation, from superclass to subclass. 0 Further, since super( ) must be the first statement executed in a subclass constructor, this order is the same whether or not super() is used. If super( ) is not used, then the default or parameterless constructor of each superclass will be executed. Eg:-

Chapter 1 - OOP Principles

88

// Demonstrate when constructors are called. 0 The output from this program is // Create a super class. shown here: class A { A() { System.out.println("Inside A's constructor."); } } // Create a subclass by extending class A. class B extends A { 0 As you can see, the constructors B() { are called in order of derivation. If System.out.println("Inside B's constructor."); you think about it, it makes sense } that constructors are executed in } order of derivation. Because a // Create another subclass by extending B. superclass has no knowledge of class C extends B { any subclass, any initialization it C() { needs to perform is separate from System.out.println("Inside C's constructor."); and possibly prerequisite to any } initialization performed by the } subclass. Therefore, it must be class CallingCons { executed first. public static void main(String args[]) { C c = new C(); } } Chapter 1 - OOP Principles 89

When Constructors Are Called(cont)

1. Inheritance(cont)

Inside As constructor Inside Bs constructor Inside Cs constructor

2. Polymorphism
Method Overriding
0 In a class hierarchy, when a method in a subclass has the

same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. 0 The version of the method defined by the superclass will be hidden. Consider the following:

Chapter 1 - OOP Principles

90

2. Polymorphism(cont)
Method Overriding(cont)
// Method overriding. class A { int i, j; A(int a, int b) { i = a; j = b; } void show() { // display i and j System.out.println("i and j: " + i + " " + j); } }
class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } // display k this overrides show() in A void show() { System.out.println("k: " + k); } } class Override { public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); // this calls show() in B } 91 }

Chapter 1 - OOP Principles

2. Polymorphism(cont)
Method Overriding(cont)
0 The output produced by this program is shown here:

k: 3 0 When show( ) is invoked on an object of type B, the version of show( ) defined within B is used. That is, the version of show( ) inside B overrides the version declared in A. 0 If you wish to access the superclass version of an overridden function, you can do so by using super. For example, in this version of B, the superclass version of show( ) is invoked within the subclass version. This allows all instance variables to be displayed.

Chapter 1 - OOP Principles

92

2. Polymorphism(cont)
Method Overriding(cont)
0 If you substitute this version of A

class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { super.show(); //calls A's show() System.out.println("k: " + k); }

Chapter 1 - OOP Principles

into the previous program, you will see the following output: i and j: 1 2 k: 3 0 Here, super.show( ) calls the superclass version of show( ). 0 Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded. 0 For example, consider this modified version of the preceding example: 93

2. Polymorphism(cont)
// Create a subclass by extending class A. class B extends A { // Methods with differing type int k; //signatures are overloaded not B(int a, int b, int c) { // overridden. super(a, b); class A { k = c; int i, j; } A(int a, int b) { void show(String msg) {// overload i = a; show() j = b; System.out.println(msg + k); } } } // display i and j class Override { void show() { public static void main(String args[]) { System.out.println("i and j: " + i + " + B subOb = new B(1, 2, 3); j); subOb.show("This is k: "); //calls show() } in B } subOb.show(); // this calls show()94 in A Chapter 1 - OOP Principles }

Method Overriding(cont)

2. Polymorphism(cont)
Method Overriding(cont)
0 The output produced by this program is shown here:

This is k: 3 i and j: 1 2 0 The version of show( ) in B takes a string parameter. This makes its type signature different from the one in A, which takes no parameters. Therefore, no overriding (or name hiding) takes place.

Chapter 1 - OOP Principles

95

2. Polymorphism(cont)
Method Overriding(cont)
Why Overridden Methods?
0 As stated earlier, overridden methods allow Java to support run-time 0

0 0 0

polymorphism. Polymorphism is essential to object-oriented programming for one reason: it allows a general class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods. Overridden methods are another way that Java implements the one interface, multiple methods aspect of polymorphism. Part of the key to successfully applying polymorphism is understanding that the superclasses and subclasses form a hierarchy which moves from lesser to greater specialization. Used correctly, the superclass provides all elements that a subclass can use directly. It also defines those methods that the derived class must implement on its own. This allows the subclass the flexibility to define its own methods, yet still enforces a consistent interface. Thus, by combining inheritance with overridden methods, a superclass can 96 define the general form of the methods that will be used by all of its subclasses.

2. Polymorphism(cont)
Method Overriding(cont)
Using final with Inheritance 0 The keyword final has three uses. First, it can be used to create the equivalent of a named constant. The other two uses of final apply to inheritance. First Use : Using final to Prevent Overriding 0 While method overriding is one of Javas most powerful features, there will be times when you will want to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden. The following fragment illustrates final:
Chapter 1 - OOP Principles 97

2. Polymorphism(cont)
Method Overriding(cont)
Example on First Use class A { final void display() { System.out.println("This is a final method."); } } class B extends A { void display() { // ERROR! Can't override. System.out.println("Illegal!"); } } 0 Because display( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-time error will result. Chapter 1 - OOP Principles 98

2. Polymorphism(cont)
Method Overriding(cont)
Second Use : Using final to Prevent Inheritance 0 Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final. 0 Declaring a class as final implicitly declares all of its methods as final, too. As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.

99

2. Polymorphism(cont)
Method Overriding(cont)
final class A { // ... } // The following class is illegal. class B extends A { // ERROR! Can't subclass A // ... } 0 As the comments imply, it is illegal for B to inherit A since A is declared as final.

Chapter 1 - OOP Principles

100

2. Polymorphism(cont)
The Object Class
0 There is one special class, Object, defined by Java. 0 All other classes are subclasses of Object. That is, Object is a

superclass of all other classes. This means that a reference variable of type Object can refer to an object of any other class. Also, since arrays are implemented as classes, a variable of type Object can also refer to any array. 0 Object defines the following methods, which means that they are available in every object.

Chapter 1 - OOP Principles

101

Method Object clone( )

Purpose Creates a new object that is the same as the object being cloned. Determines whether one object is equal to another. Called before an unused object is recycled. Obtains the class of an object at run time Returns the hash code associated with the invoking object.

boolean equals(Object object)

void finalize( )

Class getClass( ). int hashCode( )

void notify( )

Resumes execution of a thread waiting on the invoking object.


Returns a string that describes the object.
Chapter 1 - OOP Principles 102

String toString( )

3.Abstract Classes
0 Abstraction refers to the ability to make a class abstract in OOP.

An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class. 0 This is typically how abstract classes come about during the design phase. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own. 0 Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration somewhere before the class keyword.
Chapter 1 - OOP Principles 103

3.Abstract Classes(cont)
0 There are situations in which you will want to define a superclass

that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. 0 Such a class determines the nature of the methods that the subclasses must implement. One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method. 0 You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the superclass. Thus, a subclass must override themit cannot simply use the version defined in the superclass. Chapter 1 - OOP Principles 104

public abstract class Employee { private String name; private String jobTitle; public Employee(String name, String jobTitle) { this.name = name; this. jobTitle = jobTitle; } public void getEmployee(){ System.out.println(Employee Info); System.out.println(Name : + name + JobTitle : + jobTitle); } } 0 Notice that nothing is different in this Employee class. The class is now abstract, but it still has two fields, one methods, and one constructor. 0 Now if you would try as follows:
Chapter 1 - OOP Principles 105

3.Abstract Classes(cont)

3.Abstract Classes(cont)
public class AbstractDemo { public static void main(String [] args) { Employee e = new Employee(Tenagne", Secretary); } } 0 When you would compile above class then you would get following error: Employee is abstract; cannot be instantiated Employee e = new Employee(Tenagne", Secretary);

Chapter 1 - OOP Principles

106

Extending Abstract Class:

3.Abstract Classes(cont)

0 We can extend Employee class in normal way as follows:

public class Salary extends Employee { private double salary; public Salary(String name, String jobTitle, double salary){ super(name, jobTitle); setSalary(salary); } public double getSalary() { return salary; } public void setSalary(double newSalary) { if(newSalary >= 0.0) { salary = newSalary; } } Chapter 1 - OOP Principles }

107

3.Abstract Classes(cont)
Extending Abstract Class(cont):
0 Here we cannot instantiate a new Employee, but if we instantiate a

new Salary object, the Salary object will inherit the two fields and one method from Employee. public class AbstractDemo { public static void main(String [] args) { Salary sal = new Salary(Adenagir", Security, 3600.00); sal.getEmployee(); sal.getSalary(); } }
Chapter 1 - OOP Principles 108

3.Abstract Classes(cont)
0 Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Javas approach to run-time polymorphism is

implemented through the use of superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object.

Chapter 1 - OOP Principles

109

3.Abstract Classes(cont)
0 If you want a class to contain a particular method but you want the

Abstract Methods

actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract. 0 The abstract keyword is also used to declare a method as abstract. An abstract methods consist of a method signature, but no method body. 0 Abstract method would have no definition, and its signature is followed by a semicolon, not curly braces. 0 To declare an abstract method, use this general form: abstract type name(parameter-list); 0 As you can see, no method body is present. 0 Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the 110 new operator. Such objects would be useless, because an abstract class is not fully defined.

3.Abstract Classes(cont)
Abstract Methods(cont)
0 Also, you cannot declare abstract constructors, or abstract

static methods. 0 Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract. 0 Example: public abstract class Employee { private String name; private String jobTitle; public abstract double computeTax(); //Remainder of class definition } Chapter 1 - OOP Principles 111

3.Abstract Classes(cont)
Abstract Methods(cont)
0 Declaring a method as abstract has two results:
0 The class must also be declared abstract. If a class contains an

abstract method, the class must be abstract as well. 0 Any child class must either override the abstract method or declare itself abstract.

0 A child class that inherits an abstract method must override it. If they do not, they must be abstract, and any of their children must override it. 0 Eventually, a descendant class has to implement the

abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated.
Chapter 1 - OOP Principles 112

3.Abstract Classes(cont)
Abstract Methods(cont)
0 If Salary is extending Employee class then it is required to implement computeTax() method as follows:

public class Salary extends Employee { private double salary; public double computeTax() { return (salary * 0.35); } //Remainder of class definition } Chapter 1 - OOP Principles

113

3.2.Interfaces
0 An interface is a collection of abstract methods. 0 A class implements an interface, thereby inheriting the abstract

0
0

methods of the interface. An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements. Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. In Java, a class can inherit from only one class but it can implement more than one interface.

Chapter 1 - OOP Principles

114

3.2.Interfaces
0 Interfaces separate the implementation and defines the

structure, and this concept is very useful in cases where you need the implementation to be interchangeable. 0 Apart from that an interface is very useful when the implementation changes frequently. 0 Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can contain properties (which are also implicitly public and abstract). 0 If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class. In addition to this an interfaces can inherit other interfaces.
Chapter 1 - OOP Principles 115

3.2.Interfaces(cont)
0 An interface is similar to a class in the following ways: 1. An interface can contain any number of methods. 2. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file. 3. The bytecode of an interface appears in a .class file. 4. Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name. 0 However, an interface is different from a class in several ways,

including:
1. 2. 3. 4. 5. 6.

You cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces.
Chapter 1 - OOP Principles 116

3.2.Interfaces(cont)
Declaring Interfaces: 0 The interface keyword is used to declare an interface. 0 Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. 0 Access to the data and code is tightly controlled by an interface. 0 The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.

Chapter 1 - OOP Principles

117

3.2.Interfaces(cont)
0 Let us look at an example

public interface NameOfInterface { //Any number of final, static fields //Any number of abstract method declarations } 0 Interfaces have the following properties: 0 An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface. 0 Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. 0 Methods in an interface are implicitly public. 0 Example: interface Animal { public void eat(); public void travel(); Chapter 1 - OOP Principles 118 }

3.2.Interfaces(cont)
Implementing Interfaces: 0 When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. 0 A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration. 0 Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
Chapter 1 - OOP Principles 119

3.2.Interfaces(cont)
0 To implement an interface, include the implements clause in a class definition,

and then create the methods defined by the interface. The general form of a class that includes the implements clause looks like this: access class classname [extends superclass] [implements interface [,interface...]] { // class-body } 0 Here, access is either public or not used. 0 If a class implements more than one interface, the interfaces are separated with a comma. 0 If a class implements two interfaces that declare the same method, then the same method will be used by clients of either interface. 0 The methods that implement an interface must be declared public. 0 Also, the type signature of the implementing method must match exactly the type signature specified in the interface definition.
Chapter 1 - OOP Principles 120

0 Example(cont):

3.2.Interfaces(cont)

interface Animal { public void eat(); public void travel(); } public class Mammal implements Animal{ public void eat(){ System.out.println("Mammal eats"); } public void travel(){ System.out.println("Mammal travels"); } public int noOfLegs(){ return 0; } public static void main(String args[]){ Mammal m = new Mammal(); m.eat(); m.travel(); Chapter 1 - OOP Principles } }

Output will be: Mammal eats Mammal travels

121

3.2.Interfaces(cont)
0 When overriding methods defined in interfaces there are several

rules to be followed:
1. 2.

The signature of the interface method and the same return type or subtype should be maintained when overriding the methods. An implementation class itself can be abstract and if so interface methods need not be implemented.

0 When implementing interfaces there are several rules: 1. A class can extend only one class, but can implement many interface. 2. An interface itself can extend another interface.

Chapter 1 - OOP Principles

122

Extending Interfaces: 0 An interface can extend another interface, similarly to the way that a class can extend another class. 0 The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface. 0 The following Sports interface is extended by Hockey and Football interfaces.

3.2.Interfaces(cont)

Chapter 1 - OOP Principles

123

0 Example

3.2.Interfaces(cont)
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports.

public interface Sports { public void setHomeTeam(String name); public void setVisitingTeam(String name); } public interface Football extends Sports { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); } public interface Hockey extends Sports { public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); } Chapter 1 - OOP Principles

124

3.2.Interfaces(cont)
Extending Multiple Interfaces: 0 A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface. 0 The extends keyword is used once, and the parent interfaces are declared in a comma-separated list. 0 For example, if the Hockey interface extended both Sports and Event, it would be declared as: public interface Hockey extends Sports, Event

Chapter 1 - OOP Principles

125

3.2.Interfaces(cont) Tagging Interfaces:


0 The most common use of extending interfaces occurs when the parent interface

does not contain any methods. 0 For example, the MouseListener interface in the java.awt.event package extended java.util.EventListener, which is defined as: package java.util; public interface EventListener {} 0 An interface with no methods in it is referred to as a tagging interface. 0 There are two basic design purposes of tagging interfaces: 1. Creates a common parent: As with the EventListener interface, which is extended by dozens of other interfaces in the Java API, you can use a tagging interface to create a common parent among a group of interfaces. For example, when an interface extends EventListener, the JVM knows that this particular interface is going to be used in an event delegation scenario. 2. Adds a data type to a class: This situation is where the term tagging comes from. A class that implements a tagging interface does not need to define any methods (since the interface does not have any), but the class becomes an interface type through polymorphism.
Chapter 1 - OOP Principles 126

3.2.Interfaces(cont)
What is the difference between an Interface and an Abstract class? 0 There are quite a big difference between an interface and an abstract class, even though both look similar.
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Interface definition begins with a keyword interface so it is of type interface Abstract classes are declared with the abstract keyword so it is of type class Interface has no implementation, but they have to be implemented. Abstract classs methods can have implementations and they have to be extended. Interfaces can only have method declaration (implicitly public and abstract) and fields (implicitly public static) Abstract classs methods cant have implementation only when declared abstract. Interface can inherit more than one interfaces Abstract class can implement more than one interfaces, but can inherit only one class Abstract class must override all abstract method and may override virtual methods Interface can be used when the implementation is changing Abstract class can be used to provide some default behavior for a base class. Interface makes implementation interchangeable Interface increase security by hiding the implementation Abstract class can be used when implementing framework Abstract classes are an excellent way to create planned inheritance hierarchies and also to use as non-leaf classes in class hierarchies.
Chapter 1 - OOP Principles 127

What is the difference between a Class and an Interface? 0 A class and an interface are two different types (conceptually). 0 Theoretically a class emphasis the idea of encapsulation, while an interface emphasis the idea of abstraction (by suppressing the details of the implementation). The two poses a clear separation from one to another. 0 A class can be defined to implement an interface and also it supports multiple implementations. When a class implements an interface, an object of such class can be encapsulated inside an interface.

3.2.Interfaces(cont)

Chapter 1 - OOP Principles

128

Java - Arrays
0 Java provides a data structure, the array, which stores a fixed-size

sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. 0 Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.

Chapter 1 - OOP Principles

130

Declaring Array Variables: 0 To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. 0 Here is the syntax for declaring an array variable:
dataType[] arrayRefVar; // preferred way. or dataType arrayRefVar[]; // works but not preferred way.

Java Arrays(cont)

Note: The style dataType[] arrayRefVar is preferred. The

style dataType arrayRefVar[]comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.

0 Example: The following code snippets are examples of this syntax:

double[] myList; // preferred way. or double myList[]; // works but not preferred way.
Chapter 1 - OOP Principles 131

Creating Arrays: 0 You can create an array by using the new operator with the following syntax: arrayRefVar = new dataType[arraySize]; 0 The above statement does two things:
0 It creates an array using new dataType[arraySize]; 0 It assigns the reference of the newly created array to the variable

Java Arrays(cont)

arrayRefVar.

0 Declaring an array variable, creating an array, and assigning the

reference of the array to the variable can be combined in one statement, as shown below: dataType[] arrayRefVar = new dataType[arraySize]; 0 Alternatively you can create arrays as follows: dataType[] arrayRefVar = {value0, value1, ..., valuek}; 0 The array elements are accessed through Chapter 1 - OOP Principles the index. Array indices 132 are 0-based; that is, they start from 0 to arrayRefVar.length-1.

0 Example: 0 Following statement declares an array variable, myList, creates an array

Java Arrays(cont)

of 10 elements of double type, and assigns its reference to myList.: double[] myList = new double[10]; 0 Following picture represents array myList. Here myList holds ten double values and the indices are from 0 to 9.

Chapter 1 - OOP Principles

133

Processing Arrays: 0 When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known. 0 Example: 0 Here is a complete example of showing how to create, initialize and process arrays: public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); This output: } 1.9 // Summing all elements 2.9 double total = 0; for (int i = 0; i < myList.length; i++) { 3.4 total += myList[i]; 3.5 } Total is 11.7 System.out.println("Total is " + total); Max is 3.5 // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) Chapter 1 - OOP Principles 134 max = myList[i]; }

Java Arrays(cont)

Java Arrays(cont)
Passing Arrays to Methods: 0 Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array: public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } } 0 You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2: printArray(new int[]{3, 1, 2, 6, 4, 2});
Chapter 1 - OOP Principles 135

Java Arrays(cont)
Returning an Array from a Method: 0 A method may also return an array. For example, the method shown below returns an array that is the reversal of another array: public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0; i = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } result result; }

Chapter 1 - OOP Principles

136

0 The Arrays Class: 0 The java.util.Arrays class contains various static methods for sorting and

Java Arrays(cont)

searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.

Methods with Description public static int binarySearch(Object[] a, Object key) Searches the specified array of Object ( Byte, Int , double etc) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, (-(insertion point + 1). public static boolean equals(long[] a, long[] a2) Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other premitive data types ( Byte, short, Int etc.) public static void fill(int[] a, int val) Assigns the specified int value to each element of the specified array of ints. Same method could be used by all other premitive data types ( Byte, short, Int etc.) public static void sort(Object[] a) Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. Same method could be used by all other premitive data types ( Byte, short, Int etc.) Chapter 1 - OOP Principles 137

Java String
0 Strings, which are widely used in Java programming, are a sequence of

characters. In the Java programming language, strings are objects. 0 The Java platform provides the String class to create and manipulate strings. Creating Strings: 0 The most direct way to create a string is to write: String greeting = "Hello world!"; 0 Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'. 0 As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:
Chapter 1 - OOP Principles 138

Java String(cont)
String Length: 0 Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. 0 After the following two lines of code have been executed, len equals 17: public class StringDemo{ public static void main(String args[]){ String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); System.out.println( "String Length is : " + len ); } } 0 This would produce following result: Chapter 1 - OOP Principles 139 String Length is : 17

Java String(cont)
Concatenating Strings: 0 The String class includes a method for concatenating two strings: string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. 0 You can also use the concat() method with string literals, as in: "My name is ".concat("Zara"); 0 Strings are more commonly concatenated with the + operator, as in: "Hello," + " world" + "!" which results in: "Hello, world!" 0 Let us look at the followinge example: public class StringDemo{ public static void main(String args[]){ String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod"); } } Chapter 1 - OOP Principles 140 0 This would produce following result: Dot saw I was Tod

Java String(cont)
Creating Format Strings: 0 You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object. 0 Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of: System.out.printf("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the string " + "is %s", floatVar, intVar, stringVar); you can write: String fs; fs = String.format("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the string " + "is %s", floatVar, intVar, stringVar); 141 System.out.println(fs); Chapter 1 - OOP Principles

Java String(cont)
SN Methods with Description 1 2 3 4 5 6 char charAt(int index) Returns the character at the specified index. int compareTo(Object o) Compares this String to another Object. int compareTo(String anotherString) Compares two strings lexicographically. int compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case differences. String concat(String str) Concatenates the specified string to the end of this string. boolean contentEquals(StringBuffer sb) Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer. static String copyValueOf(char[] data) Returns a String that represents the character sequence in the array specified. static String copyValueOf(char[] data, int offset, int count) Returns a String that represents the character sequence in the array specified. boolean endsWith(String suffix) Tests if this string ends with the specified suffix. boolean equals(Object anObject) Chapter 1 - OOP Principles Compares this string to the specified object. 142

7 8

9 10

SN 11 12

Methods with Description

Java String(cont)

boolean equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case considerations. byte getBytes() Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. byte[] getBytes(String charsetName Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Copies characters from this string into the destination character array. int hashCode() Returns a hash code for this string. int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character. int indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. int indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. String intern() Returns a canonical representation for the string object.

13

14 15 16 17

18 19

20

Chapter 1 - OOP Principles

143

SN 21 22

Methods with Description

Java String(cont)

int lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character. int lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. int lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the specified substring. int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index. int length() Returns the length of this string. boolean matches(String regex) Tells whether or not this string matches the given regular expression. boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) Tests if two string regions are equal. boolean regionMatches(int toffset, String other, int ooffset, int len) Tests if two string regions are equal. String replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. String replaceAll(String regex, String replacement Chapter 1 - OOP Principles 144 Replaces each substring of this string that matches the given regular expression with the given replacement.

23 24

25 26 27 28 29

30

SN 31

Methods with Description

Java String(cont)

String replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement. String[] split(String regex) Splits this string around matches of the given regular expression. String[] split(String regex, int limit) Splits this string around matches of the given regular expression. boolean startsWith(String prefix) Tests if this string starts with the specified prefix. boolean startsWith(String prefix, int toffset) Tests if this string starts with the specified prefix beginning a specified index.

32 33 34 35

36
37 38 39 40

CharSequence subSequence(int beginIndex, int endIndex) Returns a new character sequence that is a subsequence of this sequence.
String substring(int beginIndex) Returns a new string that is a substring of this string. String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string. char[] toCharArray() Converts this string to a new character array. String toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale. Chapter 1 - OOP Principles 145

SN 41

Methods with Description

Java String(cont)

String toLowerCase(Locale locale) Converts all of the characters in this String to lower case using the rules of the given Locale. String toString() This object (which is already a string!) is itself returned. String toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale. String toUpperCase(Locale locale) Converts all of the characters in this String to upper case using the rules of the given Locale. String trim() Returns a copy of the string, with leading and trailing whitespace omitted. static String valueOf(primitive data type x) Returns the string representation of the passed data type argument.

42 43

44

45 46

Chapter 1 - OOP Principles

146

Java String(cont) Java String compare to determine Equality


0 java string compare can be done in many ways as shown below.

Depending on the type of java string compare you need, each of them is used. 0 * == Operator * equals method * compareTo method 0 Comparing using the == Operator 0 The == operator is used when we have to compare the String object references. If two String variables point to the same object in memory, the comparison returns true. Otherwise, the comparison returns false. Note that the == operator does not compare the content of the text present in the String objects. It only compares thereferences the 2 Strings are pointing to. The following Program would print The strings are unequal In the first case and The strings are equal in the second case.
Chapter 1 - OOP Principles 147

Java String(cont) Java String compare to determine Equality(cont)


public class StringComparision1 { public static void main(String[] args) { String name1 = "Bob"; String name2 = new String("Bob"); String name3 = "Bob"; // 1st case if (name1 == name2) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } // 2nd case if (name1 == name3) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } } Chapter 1 - OOP Principles }

148

Java String(cont) Java String compare to determine Equality(cont)


0 Comparing using the equals Method 0 The equals method is used when we need to compare the content

of the text present in the String objects. This method returns true when two String objects hold the same content (i.e. the same values). The following Program would print The strings are unequal In the first case and The strings are equal in the second case. 0 Example:

Chapter 1 - OOP Principles

149

Java String(cont) Java String compare to determine Equality(cont)


public class StringComparision2 { public static void main(String[] args) { String name1 = "Bob"; String name2 = new String("Bob1"); String name3 = "Bob"; // 1st case if (name1.equals(name2)) { strings are equal."); } else { System.out.println("The strings are unequal."); } // 2nd case if (name1.equals(name3)) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); Chapter 1 - OOP Principles } }

System.out.println("The

150

Java String(cont) Java String compare to determine Equality(cont)


0 Comparing using the compareTo Method 0 The compareTo method is used when we need to determine the

order of Strings lexicographically. It compares char values similar to the equals method. The compareTo method returns a negative integer if the first String object precedes the second string. It returns zero if the 2 strings being compared are equal. It returns a positive integer if the first String object follows the second string. The following Program would print name2 follows name1 In the first case and name1 follows name3 in the second case. 0 Example:

Chapter 1 - OOP Principles

151

Java String(cont) Java String compare to determine Equality(cont)


public class StringComparision3 { public static void main(String[] args) { String name1 = "bob"; String name2 = new String("cob"); String name3 = "Bob"; // 1st case if (name1.compareTo(name2) == 0) { System.out.println("The strings are equal."); } else if (name1.compareTo(name2) < 0) { System.out.println("name2 follows name1"); } else { System.out.println("name1 follows name2"); } . . Chapter 1 - OOP Principles .

152

Java String(cont) Java String compare to determine Equality(cont)


. . . // 2nd case. Comparing Ascii Uppercase will be smaller then Lower Case if (name1.compareTo(name3) == 0) { System.out.println("The strings are equal."); } else if (name1.compareTo(name3) < 0) { System.out.println("name3 follows name1"); } else { System.out.println("name1 follows name3"); } } }
Chapter 1 - OOP Principles 153

Vous aimerez peut-être aussi