Upload
andersson7
View
223
Download
0
Embed Size (px)
Citation preview
8/13/2019 Introduction Java 2
1/29
8/13/2019 Introduction Java 2
2/29
Basic Programming using Java OOPS in Java
2.1Object Oriented Programming ConceptsObject orientation is a paradigm shift in programming technology. Till now programmers
used the traditional approach of procedural programming. In procedural programming,
the programmer gives a list of instructions to the computer system and the computer
carries them out. As the code became large, there was a need felt to break the code intoblocks called procedures and functions. This is known as structured programming.
Structured programming did help in maintaining manageable chunks of code but at the
same time it had many drawbacks. Many times functions and procedures have to use data
outside their boundary. As a result of this, testing a module becomes very difficult, sinceeach module has to be checked to see if it is working properly as well as to see if the
value that it changes isnt corrupted as a result. This problem is aggravated as the
program size increases. Another problem with the procedural programming was that data
was given secondary importance. Data is the most important thing in any application. Infact data is the primary reason why the application exists. But in procedural programming
more emphasis was laid on how data is going to be manipulated with the help offunctions and procedures.
These problems are solved by the object-oriented methodology. Data is given the primaryimportance in object-oriented methodology. The core of the object-oriented technology is
the object. An object incorporates both data and methods that act upon that data. To
understand this better, consider any real life object; let us take the example of a pen. Apen is an object that has characteristics (colour, nib or ball point, body of the pen, etc.)
and behaviour (a pen writes). Similarly in object-oriented technology, an object
comprises of characteristics (data) and behaviour (methods that operate on data). Thisconcept is in contrast to procedural programming where data and functions are loosely
coupled.
When we talk about object-orientation, a lot of terms like object, classes, abstraction,inheritance, polymorphism and encapsulation come to our mind. We have already
discussed what an object is, let us now explore the rest of the terms one by one.
2.1.1 ClassA class is nothing but a collection of similar objects. These objects must have the samedata structure and behaviour or methods. For example, sparrow, parrot, and robin, all
belong to the class birdsince they all have same attributes and behaviour.
8/13/2019 Introduction Java 2
3/29
8/13/2019 Introduction Java 2
4/29
Basic Programming using Java OOPS in Java
Inheritance is the sharing of attributes and operations among classes based on a
hierarchical relationship. Inheritance also facilitates reusability since all the attributes andbehaviour of the main class are available to its sub-classes. For example, in the Order
Processing application, we have an object called Item(refer to fig. 2.1). Let us suppose
that the company deals in computer hardware. Then this item can be sub-classed intoPrinter, Stationary, and Floppydisk. Now since all these sub-classes have some common
attributes like, itemno, description, rate, quantity on hand and reorder level, we have keptthese under the super classItem. Printersub-class will have all these attributes plus twomore attributes of its own type of the printer(Laserjet or Inkjet) and number of pages
printed per minute. Stationaryclass again have all of the super classs attributes plus one
more attribute size of the paper. Floppydisk class also has all of the super classs
attributes and two of its own capacity and size. Fig. 2.2 shows this inheritancepictorially.
Fig. 2.2 Inheritance
2.1.5 PolymorphismPolymorphism is the ability of a method or an operation to behave differently with
different objects. For example, showfunction would behave differently for class Printerand class Floppydisk (refer to fig. 2.3). When applied to an object of Printerclass, show
function would display Item No., Description, Rate, Quantity on hand, Reorder level,
type of the printer and pages printed per minute. And when show function is applied to anobject of FloppyDisk class, it would display Item No., Description, Rate, Quantity on
hand, Reorder level, Capacity and size.
Item
Item No
Description
RateQuantity on hand
Reorder level
Printer
Type
PagesPerMinute
Stationary
Size
FloppyDisk
Capacity
Size
8/13/2019 Introduction Java 2
5/29
Basic Programming using Java OOPS in Java
Fig. 2.3 Polymorphism
2.2Creating Classes And ObjectsNow that we are familiar with the object-oriented programming approach and the Java
programming constructs, let us now write Java program to create Item class. We havealready identified the data and methods for this class. The following Java code can be
written to createItemclass.
cl ass I t em{pr i vat e i nt i t emno;pr i vat e St r i ng descr i pt i on;pr i vat e f l oat r at e;pr i vat e i nt qoh;pr i vat e i nt rol ;
publ i c voi d di spl ay( ) {System. out . pr i nt l n( " I t em Det ai l s") ;System. out . pr i nt l n( " - - - - - - - - - - - - " ) ;
System. out . pr i nt l n( "I t em Number : "+i t emno) ;Syst em. out . pr i nt l n( "Descri pt i on : "+descri pt i on) ;Syst em. out . pr i nt l n( "Rat e : "+r at e) ;Syst em. out . pr i nt l n( "Quant i t y on hand : "+qoh) ;Syst em. out . pr i nt l n( "Reor der Level : "+r ol ) ;
}publ i c voi d changeQOH( i nt qt y, char st at us) {
i f ( st at us==' A' )
Item Details
Item No : 1000051
Description : HP Printer
Rate : 10,500.00
Quantity on Hand : 112
Reorder level : 50Type of Printer : LaserJet
Pages Per Minute : 8
Item Details
Item No : 1001115
Description : 3M Floppy disk
Rate : 215.00
Quantity on Hand : 567Reorder level : 75
Capacity : 1.44 MB
Size : 3.5 inches
Show Function
Printer
FloppyDisk
8/13/2019 Introduction Java 2
6/29
Basic Programming using Java OOPS in Java
qoh=qoh+qt y;el se
i f ( stat us==' S' )qoh=qoh- qt y;
}publ i c voi d accept Det ai l s( i nt i no, St r i ng desc, f l oat r t , i nt
qt y, i nt r eor der ) {
i t emno=i no;descr i pt i on=desc;r at e=r t ;qoh=qt y;r ol =r eor der ;
}}
Listing 2.1 Definition of Item class
Let us now understand this piece of code. This code has created a class calledItem. This
class has five attributes and three functions. You would have noticed the access specifiers
publicandprivate, along with the definition of the attributes and methods of the classItem. We will deal with access specifiers in detail in chapter 3. As of now you can
understand that if any attribute or method of a class is declared as public, it will be
available to all the other classes. If an attribute or a method of a class is declared asprivate, it will not be able available to any other class except for the class in which it is
declared. Now since the data of an object should not be available to the object of other
classes, we have declared it as private in this example.
+ You could have declared some of the attributes as public also. Declaring anattribute or method as public or private is dependent on the application that you are
designing.
We want to design our application in such a manner so that methods should be the onlyway by which one can access the data of Itemclass. This is the reason why all methods
have been declared as public in the above example. You would have also noticed a newdata type called String. String is not actually a data type, its a class defined in packagejava.lang.
+ Numbers and characters are not objects. They are primitive data types. This is thereason for their definition and usage being different from the String object in the
above example.
Let us now understand how an object of a class is created. An object of the classItem
canbe created by giving the following command:
Item I = new Item();
This command creates an object I of the class Item. In this command, new operatorcreates an object, i.e., it allocates memory for the classs data and a special method
defined in the class is called. This method is known as a constuctor. We will deal with
constructors later in this chapter.
8/13/2019 Introduction Java 2
7/29
Basic Programming using Java OOPS in Java
A method of a class can be called by using dot(.) notation. For example, c hangeQOH
method of classItemcan be called as:I.changeQOH(20,A);
whereIis the object for which quantity on hand is being changed.
The complete listing of the program that defines Item class and uses it to create and
manipulate an object is given below:
cl ass I t em{pr i vat e i nt i t emno;pr i vat e St r i ng descr i pt i on;pr i vat e f l oat r at e;pr i vat e i nt qoh;pr i vat e i nt rol ;publ i c voi d di spl ay( ) {
System. out . pr i nt l n( " I t em Det ai l s") ;System. out . pr i nt l n( " - - - - - - - - - - - - " ) ;System. out . pr i nt l n( "I t em Number : "+i t emno) ;
Syst em. out . pr i nt l n( "Descri pt i on : "+descri pt i on) ;Syst em. out . pr i nt l n( "Rat e : "+r at e) ;Syst em. out . pr i nt l n( "Quant i t y on hand : "+qoh) ;Syst em. out . pr i nt l n( "Reor der Level : "+r ol ) ;
}publ i c voi d changeQOH( i nt qt y, char st at us) {
i f ( st at us==' A' )qoh=qoh+qt y;
el sei f ( stat us==' S' )
qoh=qoh- qt y;}publ i c voi d accept Det ai l s( i nt i no, St r i ng desc, f l oat r t , i nt
qt y, i nt r eor der ) {i t emno=i no;descr i pt i on=desc;r at e=r t ;qoh=qt y;r ol =r eor der ;
}publ i c stat i c voi d mai n( St r i ng ar gs[ ] ) {
I t em I =new I t em( ) ;St r i ng d = new St r i ng( "Nut s & Bol t s" ) ;I . accept Det ai l s( 1, d, ( f l oat ) 23. 56, 100, 23) ;I . di spl ay( ) ;
I . changeQOH( 20, ' A' ) ;I . di spl ay( ) ;I . changeQOH( 20, ' S' ) ;I . di spl ay( ) ;
}}
Listing 2.2 Creating object of Item class (Item.java file)
The working of this program is given below:
8/13/2019 Introduction Java 2
8/29
Basic Programming using Java OOPS in Java
1. In the main function, an object I of Item class is created and an object d of Stringclass is created.
2. Method acceptDetails of object I is called which will allocate 1 to itemno, convert23.56 to float and allocate it to rate, allocate 100 to qohand 23 to rol. It also accepts aStringobject dand allocates it to description.
3. Method displayis called which will display the item details.4. Method changeQOHis called with two parameters 20 and A. This will add 20 tothe existing qoh.
5. Method displayis called again.6. Method changeQOH is called again with two parameters 20 and S. This will
subtract 20 from the existing qoh.7. Method displayis called again.The output of this program is given below:
I t em Det ai l s- - - - - - - - - - - - - - -I t em Number : 1Descr i pt i on : Nut s & Bol t sRate : 23. 56Quant i t y on Hand : 100Reor der Level : 23
I t em Det ai l s- - - - - - - - - - - - - - -I t em Number : 1Descr i pt i on : Nut s & Bol t sRate : 23. 56Quant i t y on Hand : 120
Reor der Level : 23
I t em Det ai l s- - - - - - - - - - - - - - -I t em Number : 1Descr i pt i on : Nut s & Bol t sRate : 23. 56Quant i t y on Hand : 100Reor der Level : 23
Note that the methods of the same class like acceptDetails, can access the class variables
or methods directly. For example, in acceptDetails function, we gave the command
itemno=ino, which assigns the value of variable inoto itemno. But in the main functionthe method display of class Item is called asI.display(). This means that you are not able
to access the attributes or methods of a class in another class or function directly. Youwill have to access methods or attributes through an object, i.e., you must create an object
of that class first and then access its public attributes or methods via that object.
8/13/2019 Introduction Java 2
9/29
Basic Programming using Java OOPS in Java
2.3Memory ManagementYou have seen that newoperator can be used to create a new object in Java. This operatorallocates right amount of memory to each objects data. Memory management in Java is
dynamic and automatic. This simply means that it is perfectly possible for you to create
just a reference to an object and allocate memory to it at a later point of time with the
help of newoperator. This is depicted in the example given below:
.I t em I ;..I = new I t em( ) ;
Let us now see how memory is allocated to objects of a class. Each object of a class will
have memory allocated for its individual attributes, but all the objects of the same class
will share the same methods. This simply means that whenever an object of a class is
created with the help of newoperator, memory is allocated for its attributes and not for itsmethods. This is depicted in fig. 2.4.
Fig. 2.4 Memory Management
Since memory management in Java is automatic, you dont have to deallocate the
memory that an object uses. Java has a garbage collector that looks for the objects that
are no longer in use and reclaims the memory used by those objects.
Item A Item B
acceptDetails
display
Methods of class Item
Memor
1Nuts & Bolts
23.56
100
23
2Hammer
75.89
156
50
8/13/2019 Introduction Java 2
10/29
Basic Programming using Java OOPS in Java
Many times an object has to perform certain operations when it is destroyed. Forexample, a program could be holding some resource like a file handle, or a window
character font, which you might want to free before that object is destroyed. For this
purpose you can override a method calledfinalize(). This method is invoked just beforethat object is reclaimed by the garbage collector. This process of defining the finalize()
method is known as finalization. The general form offinalize()method is:pr ot ected voi d f i nal i ze( ) {..}
However, you must note one thing. There is no way of knowing when the garbage
collector is invoked andfinalize()method is called just before the garbage collection. For
this reason you can never be sure of when and also if at all yourfinalize()method will be
invoked.
+ You have to explicitly allocate memory to objects with the help of new operator,but you dont have to explicitly free it.Runtime class
Runtime class encapsulates the run-time environment. Since the run-time environment
already exist, you cannot instantiate the Runtime object. You can, however, get the
reference to the current run-time environment with the help of getRuntime()method. Youcan explicitly call garbage collection by using method gc(). The following piece of code
invokes the garbage collection.
Runt i me r =Runt i me. getRunt i me( ) ;r . gc( ) ;
2.4CastingIn a Java program, many times a data value of one type has to be converted to a value ofanother data type. For example, one might have to convert an int to float or a float todouble. Casting is the process of getting a new value that has a different data type than its
source. Casting can take place between primitive data types (int, float, boolean, etc.) or
between objects (String, Point, Integer, etc.) or between a primitive data type and anobject.
8/13/2019 Introduction Java 2
11/29
Basic Programming using Java OOPS in Java
2.4.1 Casting Primitive Data TypesCasting between data value of primitive data types simply converts a data value of a
primitive data type to another primitive data type. However, boolean values cannot be
used in casting as they can hold only two values true or false. Casting usually happens
among numeric values. In case the destination can hold a larger value than the source (asin the case of converting intto long, casting is done automatically. This means that one
can use an intas long. This is because when a smaller value is converted to a larger value,
there is no loss of data involved.
However, if the destination cannot hold larger value than the source, explicit casting must
be done. Explicit casting is done in the following way:( dat a t ype) val ue
The following piece of code converts afloatvalue to an intvalue.
.i nt i ;f l oat f =6. 7;
i =( i nt ) f ;.
However, data will be lost in this case. Variable iwill have a value 6 since it will be ableto hold only integer part of the data. Another example given below converts an integer to
double.
.i nt i =1078;doubl e d;
d=( doubl e) i ;.
2.4.2 Casting ObjectsAs a primitive data type value can be converted to another primitive data type value, an
object of a class can also be converted to an object of another class. But both theseclasses must be related to each other by inheritance, i.e., one class must be a subclass of
the other class. Here also casting can either be implicit or explicit.
Implicit casting happens when an object of smaller type is casted to an object of larger
type. This means that an instance of subclass can be used wherever an instance of a super
class is expected without explicitly casting. This is because all the attributes and methodsof a super class are automatically available to all of its subclasses. Refer to fig. 2.2, whichshows the inheritance relationship among Item, Printer, Stationary and FloppyDisk
classes. Item is the super class and rest are its subclasses. If there is a function thataccepts an object of Itemclass, it will also accept an object of Printeror StationaryorFloppyDiskclass.
8/13/2019 Introduction Java 2
12/29
Basic Programming using Java OOPS in Java
However, if an object of subclass has to be casted to an object of super class, explicit
casting must be done. There is one more thing that one must keep in mind while doingexplicit casting explicit casting might result in loss of information. This is because
subclass will contain more functionalities than its super class. To cast an object to another
class the following operation can be used:( cl assname) obj ect
Refer to fig.2.2 again and observe the code given below:
I t em I = new I t em( ) ;Pr i nt er P = new Pr i nt er ( ) ;I =P; / / val i d st at ement , i mpl i ci t cast i ng doneP=I ; / / i nval i d st at ement , expl i ci t cast i ng r equi r edP=( Pr i nt er ) I ; / / val i d st at ement
2.4.3 Casting Primitive Data Types to Objects or Objects to Primitive Data TypesCasting an object to primitive data type or vice-versa is not allowed at all in Java. This is
because primitive data types do not follow the concept of a class and hence they are verydifferent from objects. Since this feature of casting an object to primitive data type or
vice-versa is not allowed, Java has provided its users with an alternative. j ava. l ang
package include classes that correspond to primitive data type. For example, it has a classcalledIntegerin place of primitive data type int, similarly there are classes like Boolean,
Byte, Character, Long, Void, Double, Float, etc for each of the primitive data type.
To convert an object to primitive data type or vice-versa, you can use the methods of that
class. For example, to convert a Stringobject to an intyou can write the following code:St r i ng st r = new St r i ng( 4578) ;i nt i = I nt eger . parseI nt ( str ) ;
In the above code we have made use of methodparseIntofIntegerclass to get the integervalue of the Stringobject str.
2.5ConstructorsIn section 2.2 we had a brief introduction to constructor. Let us now understandconstructors in detail. Constructors are class methods that are used to initialise objects
data. Constructors can be declared in the same way as any other method of a class is
declared. However, a constructor will not have any return type (not even void type shouldbe mentioned) and the name of the constructor is same as the name of the class. The
following piece of code defines a constructor for theItemclass.
I t em( ) {
i t emno=0;descr i pt i on = new St r i ng( ) ;r at e=0. 0f ;qoh=0;r ol =0;
}Listing 2.3 Constructor for class Item
8/13/2019 Introduction Java 2
13/29
Basic Programming using Java OOPS in Java
This constructor assigns value to the objects data whenever it is called. A constructor
can be called as:I t em I = new I t em( ) ;
Now in program listing 2.2 we did initialise an object I in the same manner as given
above. But at that time we did not define any constructor method, but still the program
didnt give us any error. That was because Java automatically provides every class with adefault constructor whenever user does not give any. Therefore, in program listing 2.2,
the default constructor of classItemwas called. If the user writes a constructor method inthe class, that method will be called when an object of that class is created.
2.5.1 Creating Multiple ConstructorsA class can have multiple constructors also. But the question is why would anyone need
multiple constructors for a class. Since constructors are the way to initialise an object,
one might want to create objects in a variety of way. For example, one might want that
when I t em I = new I t em( ) command is given, all numeric data must be assigned
0 and all character data must be assigned blank spaces. That is what constructor definedin listing 2.3 is doing. Now, one might also want that when I t em I = new
I t em( st r ) is given (where str is a String object), all numeric data must be assigned avalue 0 and description must have a value given by the String str. Similarly one can
create other types of constructors defined for the classItem. The constructor that is called
in the program will depend on the way an object was created at run time. Listing 2.4gives the complete code for Item class with two constructors and it also shows how
objects can be created in different ways.
cl ass I t em{pr i vat e i nt i t emno;pr i vat e St r i ng descr i pt i on;pr i vat e f l oat r at e;pr i vat e i nt qoh;pr i vat e i nt rol ;
publ i c voi d di spl ay( ) {System. out . pr i nt l n( " I t em Det ai l s") ;System. out . pr i nt l n( " - - - - - - - - - - - - " ) ;System. out . pr i nt l n( "I t em Number : "+i t emno) ;Syst em. out . pr i nt l n( "Descri pt i on : "+descri pt i on) ;Syst em. out . pr i nt l n( "Rat e : "+r at e) ;Syst em. out . pr i nt l n( "Quant i t y on hand : "+qoh) ;Syst em. out . pr i nt l n( "Reor der Level : "+r ol ) ;
}
publ i c voi d changeQOH( i nt qt y, char st at us) {i f ( st at us==' A' )
qoh=qoh+qt y;el se
i f ( stat us==' S' )qoh=qoh- qt y;
}
8/13/2019 Introduction Java 2
14/29
Basic Programming using Java OOPS in Java
publ i c voi d accept Det ai l s( i nt i no, St r i ng desc, f l oat r t , i ntqt y, i nt r eor der ) {
i t emno=i no;descr i pt i on=desc;r at e=r t ;qoh=qt y;
r ol =r eor der ;}
I t em( ) { / / Const r uct or 1i t emno=0;descri pt i on=nul l ;r at e=0. 0f ;qoh=0;r ol =0;
}I t em( St r i ng st r ) { / / Const r uct or 2
i t emno=0;
descri pt i on=st r ;r at e=0. 0f ;qoh=0;r ol =0;
}}
Listing 2.4 Class Item with constructors (Item.java file)
i mpor t I t em;
cl ass Tr yI t em{publ i c stat i c voi d mai n( St r i ng ar gs[ ] ) {
I t em i =new I t em( ) ; / / Cal l s Const r uct or 1i . di spl ay( ) ;
St r i ng d = new St r i ng( "Nut s & Bol t s" ) ;I t em j =new I t em( d) ; / / Cal l s Const r uct or 2
j . di spl ay( ) ;
/ * I nval i d as t he decl ar at i on does not mat ch any const r uct ordef i ned i n t he cl ass */
I t em k=new I t em( 1, d) ;k. di spl ay( ) ;
}
}Listing 2.5 Creating Item objects (TryItem.java file)
8/13/2019 Introduction Java 2
15/29
Basic Programming using Java OOPS in Java
+ How does the default constructor initialize objects data?In listing 2.4 the line where an object kis created will give a compile time error since theclass does not have any matching constructor. The classItemhas only two constructors
one that accepts nothing and second that accepts an object of type String. This call tries tocall a constructor that accepts an integer and a Stringobject, which does not exist in the
class. Once you have created this I t em. j avafile, compile it to createI t em. cl assfile.To create anItemobject, include theItemclass in the program where the object has to be
created. In listing 2.5 this task is done with the help of statement i mport I t em ( I t em
Cl ass shoul d be i n t he same di r ect or y) . This statement includes the
definition ofItemclass at compile-time.
In listing 2.5, objects iandj are created in different manner and thus they call different
constructors. But name of both the constructors is the same. This is called constructoroverloading. But the question is how does compiler decides which call is for which
constructor in such a situation? The explanation for this is simple. A function isrecognized by its signature, which consist of function name, number of arguments it
accepts and argument type. A constructor is also a function and thus the same definitionof signature applies to it also. When a call to constructor is made, Java matches the
signature of the function that calls the constructor to the signature of the constructor
declared in the class. Then it calls the constructor that has the same signature as thecalling function.
+ When two functions of same name but different signatures are defined, it is knownas function overloading.
2.6Comparing ObjectsWhile dealing with primitive data types comparisons between two primitive data values
can be done by using equal (==) operator. For example, the following code declares twointdata values and then compares them.
cl ass Compi nt {publ i c stat i c voi d mai n( St r i ng ar gs[ ] ) {
i nt x=33;i nt y=33;
i f ( x==y)Syst em. out . pr i nt l n( "Equal ") ;
el seSyst em. out . pr i nt l n( "Not Equal ") ;
}}
Listing 2.6 Comparing primitive data types (Compint.java file)
8/13/2019 Introduction Java 2
16/29
Basic Programming using Java OOPS in Java
The output of this program would be Equal since both x and y have the same value.Now let us write the same program by using Integer class objects.
cl ass CompI nt eger{publ i c stat i c voi d mai n( St r i ng ar gs[ ] ) {
I nt eger x=new I nt eger ( 33) ;I nt eger y=new I nt eger ( 33) ;
i f ( x==y)Syst em. out . pr i nt l n( "Equal ") ;
el seSyst em. out . pr i nt l n( "Not Equal ") ;
}}
Listing 2.7 Comparing objects using == (CompInteger.java file)
The output of this program, however, would be NotEqual even when both objects have the same value
33. The reason is that == compares two objects andnot the value of the objects and since x and y are
different objects, the output is Not Equal. This is
explained in fig. 2.5
The same program would give the output asEqual when object y is declared as:I nt eger y;y=x;
This is because now only one object has been
created with a value 33. Object y is not allocated
memory as of now since the constructor method
has not been used. So y is simply a reference toan object of typeIntegerbut it is not pointing to
any object right now. After the statement y=x is
given, y starts pointing to the same object as x ispointing to. Fig. 2.6 makes this thing clear.
Therefore, two objects cant be compared using == operator in terms of the value they
contain. To compare the values contained by two objects equal s( ) method can be used.
Program listing 2.8 gives the code for comparing values contained by two Integer objects.
Memory
X Y
Fig. 2.6 Memory allocation for
variables that oint to the same ob ect
33
Memory
X Y
Fig. 2.5 Memory allocation for
different ob ects
33 33
8/13/2019 Introduction Java 2
17/29
Basic Programming using Java OOPS in Java
cl ass CompI nt eger{publ i c stat i c voi d mai n( St r i ng ar gs[ ] ) {
I nt eger x=new I nt eger ( 33) ;I nt eger y=new I nt eger ( 33) ;
i f ( x. equal s(y) )
Syst em. out . pr i nt l n( "Equal ") ;el se
Syst em. out . pr i nt l n( "Not Equal ") ;}
}
Listing 2.8 Comparing the values contained by two Integer objects (CompInteger.java file)
2.7InheritanceWe had a small introduction to the concept on Inheritance in section 2.1.4. Let us now
understand how it is implemented. We have already declared the Item class with fiveattributes, three methods and two constructors (refer to program listing 2.4). Let us createa subclass of Itemclass called Printer, which has two more attributes type of printer
and number of pages printed per minute.
i mpor t I t em;
/ / Def i ni ng Pr i nt er c l asscl ass Pr i nt er extends I t em{
St r i ng t ype;i nt ppm;
Pr i nt er ( ) { / / Const r uctor 1super ( ) ;t ype=nul l ;ppm=0;
}Pr i nter ( i nt i no, St r i ng desc, f l oat r t , i nt qt y, i nt
r eor der , St r i ng type, i nt ppm) {super ( i no, desc, r t , qt y, r eor der ) ; / / Const r uctor 2t hi s. t ype=t ype;t hi s. ppm=ppm;
}publ i c voi d di spl ay( ) {
super . di spl ay( ) ; / / Cal l i ng di spl ay met hod of super cl assSyst em. out . pr i nt l n( "Type of Pr i nt er : "+t ype) ;Syst em. out . pr i nt l n( "Pages per mi nut e : "+ppm) ;
}}
Listing 2.9 Printer class a subclass of Item (Printer.java file)
/ / Tr yI nher i t cl ass t hat wi l l make use of I t em and Pr i nt er cl assobj ect s
8/13/2019 Introduction Java 2
18/29
Basic Programming using Java OOPS in Java
i mpor t j ava. l ang. *;i mpor t Pr i nt er ;
cl ass Tr yI nher i t {publ i c stat i c voi d mai n( St r i ng ar gs[ ] ) {
I t em i =new I t em( 1, "Mouse" , 500. 89f , 1200, 200) ;i . di spl ay( ) ;
Pr i nt er p=new Pr i nt er ( 2, "I nkj et Pr i nt er ", 10000. 75f ,200, 35, "6P", 6) ;
p. di spl ay( ) ;}
}/ / End of Tr yI nher i t cl ass
Listing 2.10 Implementing Inheritance (TryInherit.java file)
There are two new terms introduced in listing 2.9 superand this. The superkeyword is
used to refer to the super class. In constructor 1 of Printerclass, The statement super ( )
actually calls the constructor method (number 1) of super class Item. Similarly in
constructor 2 of Printer class, statement super ( i no, desc, r t , qt y, r eor der ) callsthe constructor method (number 2) of super classItem.
The display function of Printer class calls the display function of the super class to
display first five attributes and then prints the extra two attributes. This means that bothsubclass and super class can have functions with the same name.
Constructor 2 of Printerclass also makes use of this keyword. thiskeyword is used to
refer to the current object. Note that one of the arguments of the constructor method 2 hasthe same name as the objects attribute (type). Now while assigning value of theargument typeto the objects data type, it should be clear that which variable is giving the
value and which one is accepting the value. Therefore the statement t hi s. t ype=t ypewas given. This statement implies that the objects data typewill have the same value
as the argument type of the constructor. Fig. 2.7 shows the memory allocation and
working of this program when the methods i . di spl ay( ) and p. di spl ay( )are called.
8/13/2019 Introduction Java 2
19/29
Basic Programming using Java OOPS in Java
Fig. 2.7 Working of TryInherit.java program
2.8PolymorphismAs said earlier, Polymorphism is the ability of a function to respond differently to
different objects. Polymorphism is of two types static polymorphism and dynamic
polymorphism. In Static Polymorphism, the function that has to be called is known atcompile time itself. For example, if two functions with the following signatures are
declared in a program,changeQOH(int, char)changeQOH(int)
and the command given in the program is
changeQOH(30)
The second function will be called and this is determined at compile-time itself. The fact
that the second function will be called in this case is determined by the type and numberof arguments sent to the function. Since only one argument is sent, the second function is
called. If two arguments (one int and another char) were sent, the first function wouldhave been called. This feature is also known asFunction OverloadingorEarly Binding.
Dynamic Polymorphismis also known as Late Binding. In dynamic polymorphism, the
decision of the function to be called is resolved at run-time instead of compile-time. Letus take an example to make things more clear.
We have already declaredItemand Printerclass files. Printeris a subclass ofItemclass.It is possible to declare a reference to the super class (Item) and then at run-time
Printer()
Printer(ino,desc,rt,qty,reorder,
type,ppm)
display()
Printer class functions Item class functions
Item()
Item(ino,desc,rt,qty,reorder)
display()
Object p
Object i
display()
display()
itemno
description
rateqoh
rol
typeppm
itemnodescription
rateqoh
rol
8/13/2019 Introduction Java 2
20/29
Basic Programming using Java OOPS in Java
depending on what the user enters, either an Item or a Printer object can be declared
(refer to listing 2.11).
i mpor t Pr i nt er ;i mpor t j ava. i o. *;
cl ass TryPol y{
publ i c stat i c voi d mai n( St r i ng ar gs[ ] ) {I t em i ;i nt ch=0;
whi l e ( ch! =' P' && ch! =' N' ){
Syst em. out . pr i nt l n( "Ent er N t o add a nor mal i t em or Pt o add a Pr i nt er ") ;
try{ch=Syst em. i n. r ead( ) ;
} cat ch( I OExcept i on e){Syst em. out . pr i nt l n( "Er r or ") ; }
}
i f ( ch==' P' )i =new Pr i nt er ( 1, "Laser j et ", 20000f , 100, 25, "I I I Pl us", 8) ;
el sei =new I t em( 1, "Mouse Logi t ech" , 300f , 100, 20) ;
i . di spl ay( ) ;}
}
Listing 2.11 Implementing dynamic polymorphism (TryPoly.java)
Ignore the trycatch block of the code in listing 2.11. We use trycatch block to handleerrors that might occur in a program. We will deal with them in detail in chapter 5.System.in.read is a method that is used to accept an input from the user. Note that
variable i is declared as a reference to class Item but at runtime iwill be able to hold
either an object ofItemclass or Printerclass. If the user entersNat runtime, the output of
this program would be:
I t em Det ai l s- - - - - - - - - - - - - - -I t em Number : 1Descr i pt i on : Mouse Logi t ech
Rat e : 300Quant i t y on Hand : 100Reor der Level : 20
8/13/2019 Introduction Java 2
21/29
Basic Programming using Java OOPS in Java
If the user enters Pthe output would be:
I t em Det ai l s- - - - - - - - - - - - - - -I t em Number : 1Descr i pt i on : Laser j etRat e : 20000
Quant i t y on Hand : 100Reor der Level : 25
Type of Pr i nt er : I I I Pl usPages per mi nut e : 8
Fig. 2.8 Dynamic Polymorphism
Note that depending on the user input either display function of Item or Printer class is
called. This concept is known as Dynamic Polymorphism or Late Binding.
User enters
Object p
Object i
N
Printer()
Printer(ino,desc,rt,qty,reorder,
type,ppm)
display()
Printer class functions
Item class functions
Item()
Item(ino,desc,rt,qty,reorder)
display()
P
itemno
description
rate
qohrol
type
ppm
itemnodescription
rateqohrol
8/13/2019 Introduction Java 2
22/29
8/13/2019 Introduction Java 2
23/29
Basic Programming using Java OOPS in Java
publ i c stat i c voi d mai n( St r i ng ar gs[ ] ) {I t em i ;i f ( ar gs. l engt h! =1) {
Syst em. out . pr i nt l n( "Wr ong number of argument s" ) ;Syst em. exi t ( 0) ; }
i f ( ar gs[0] . equal s(" P") ) {
i =new Pr i nt er ( 1, "Laser j et ", 20000f , 100, 25, "I I IPl us" , 8) ;
i . di spl ay( ) ; }el se
i f ( ar gs[0] . equal s(" N") ) {i =new I t em( 1, "Mouse Logi t ech" , 300f , 100, 20) ;i . di spl ay( ) ; }
el se{System. out . pr i nt l n( " I nval i d val ue. . . ") ;System. exi t ( 0) ; }
}}
Listing 2.12 Implementing Polymorphism through Command Line Arguments (TryPoly1.java)
Program Listing 2.13 accepts a number as a command line argument and print fibonacciseries from 0 till that number.
cl ass Fi bonacci {publ i c stat i c voi d mai n( St r i ng ar gs[ ] ) {
i nt a=0, b=1, c;
i f ( ar gs. l engt h! =1) {Syst em. out . pr i nt l n( "Wr ong number of argument s" ) ;Syst em. exi t ( 0) ; }
i f ( I nt eger . par seI nt ( ar gs[ 0] ) I nt eger . par seI nt ( ar gs[ 0] ) )
br eak;Syst em. out . pr i nt l n( c);
a=b;b=c;
} whi l e( t r ue) ;}
}
Listing 2.13 Fibonacci series through Command Line Arguments (Fibonacci.java)
8/13/2019 Introduction Java 2
24/29
Basic Programming using Java OOPS in Java
2.10 Reflection ClassReflection or Introspection enables one Java program to learn details of any Java class.One can find the variables, methods and constructors of a class with the help of
reflection. Listing 2.14 shows a code that prints all the methods of a class calledAdler32.
i mpor t j ava. ut i l . z i p. Adl er 32;i mpor t j ava. l ang. r ef l ect . *;
cl ass Tr yRef l ect {publ i c stat i c voi d mai n( St r i ng ar gs[ ] ) {
Adl er32 d=new Adl er32( ) ;i nt i ;
Cl ass cname = d. getCl ass( ) ;Syst em. out . pr i nt l n( "Cl ass Name : "+cname. t oSt r i ng( ) ) ;Met hod[ ] met hods = cname. get Met hods( ) ;f or ( i =0; i
8/13/2019 Introduction Java 2
25/29
Basic Programming using Java OOPS in Java
Met hod 12 : publ i c voi d j ava. ut i l . zi p. Adl er 32. updat e( i nt )Met hod 13 : publ i c voi d j ava. ut i l . zi p. Adl er 32. updat e( byt e[ ] )Method 14 : publ i c voi d
j ava. ut i l . zi p. Adl er 32. update( byt e[ ] , i nt , i nt )
Program Listing 2.15 shows the code for TryReflect1.java that prints all constructor
methods of class Alder32. The only difference between this code and listing 2.14 is thathere we have created an array of Constructor object instead of Method object (as in
listing 2.14). And then getConstructors method is used to get all constructors of that
class.
i mpor t j ava. ut i l . z i p. Adl er 32;i mpor t j ava. l ang. r ef l ect . *;
cl ass Tr yRef l ect 1{publ i c stat i c voi d mai n( St r i ng ar gs[ ] ) {
Adl er32 d=new Adl er32( ) ;i nt i ;
Cl ass cname = d. getCl ass( ) ;Syst em. out . pr i nt l n( "Cl ass Name : "+cname. t oSt r i ng( ) ) ;Const r uct or [ ] cs = cname. get Const r uct or s( ) ;f or ( i =0; i
8/13/2019 Introduction Java 2
26/29
Basic Programming using Java OOPS in Java
2.11 Case StudyCollege Student Enrolment SystemGiven below is the Case Study for Student Enrolment System from a bigger problem
domain of a College System.
Problem Statement :
The faculty determines the courses and the subjects offered for the admission. Subjectsmay be taken as a part of number of courses. Subjects will either be core subjects or
optional subjects. Generally the number of seats available for a course will be controlled.
All courses will have established entrance qualifications. The enrolment process beginswhen an applicant submits an application for a course. The applicant will also select the
course and the optional subject he or she wishes to take. The applicant will submit his or
her personal details and the results of previous examinations taken. The applicants
application is first checked for qualification and then for course and subject availability.If places are available and the applicant is qualified, he or she is enrolled as a student.
concerns
submits
selects
enrolled
Fig. 2.9 Class Diagram for Student Enrolment System
+ The notation used in the above diagram is OMT(Object Modelling Technique)where: indicates class
indicates Inheritance
indicates containment
1+ indicates course contains one or more subjects
Cours
e
Subject
Application
Applicant
Core Optional
Student
1+
8/13/2019 Introduction Java 2
27/29
Basic Programming using Java OOPS in Java
The class diagram identifies the required classes and their associations in the system. To
implement this case study we will make certain assumptions for cutting down the scopeof the problem domain. The assumptions are:
The last date for all courses is same The number of students in each course is 5 (but can be extended to any number later) The available courses are MDMC, UCO, and C++ (can be extended by the
programmer) The available subjects are C, C++, OOADS, JAVA, NT, UNIX, VB,
VC, ORACLE.
The first five students who are above the cut-off of 75% will get admitted. The qualification that the user enters will not be crosschecked from any records and is
assumed to be authentic.
Now we will define some of the classes with their methods and attributes.
publ i c cl ass Subj ect {St r i ng sname;
Subj ect ( St r i ng name){t hi s. sname = name;
}}
Listing 2.16 Code for Subject.java
publ i c cl ass Cor eSubj ect extends Subj ect {CoreSubj ect ( St r i ng name) {
super( name) ;}publ i c voi d setName(St r i ng name){
sname=name;}}
Listing 2.17 Code for CoreSubject.java which is inherited from Subject class
publ i c cl ass Opt Subj ect extends Subj ect{Opt Subj ect ( St r i ng name){
super( name) ;}publ i c voi d setName(St r i ng name){
sname=name;}
}Listing 2.18 Code for OptSubject.java which is inherited from Subject class
Similarly we can define the rest of the classes in the class diagram. We will continue with
the case study in further sessions.
8/13/2019 Introduction Java 2
28/29
Basic Programming using Java OOPS in Java
SUMMARY
An object has characteristics as well as behaviour; for example, a chair has thecharacteristics (it is made up of wood, it has four legs, etc.) and behaviour (one can sit
on it).
A class is a set of similar objects, for example, Maruti, Fiat, Santroall belong to theclass Car.
Encapsulation is the process of bundling data and methods that act on that datatogether into a single unit called class.
Inheritance is the means by which more classes can be created from existing one. The class that gets created by inheritance is known as subclass and the class from
which the subclass is created is called super class.
A subclass inherits all data and methods from its super class. Multiple subclasses can be created from a super class. new operator is used to create an object in Java. Memory management in Java is
automatic so there is no need of deallocating the memory occupied by an object.
One primitive data type can be created into another primitive data type by giving thecommand (data type)value.
One object can be cast into another object only if they are related to each other byinheritance.
There is no way to convert an object to primitive data type or vice-versa directly. Youcan use methods of objects like (Integer, Character, Byte, Float, etc.) to achieve this.
Constructors are the methods that get called when an object is created with the help ofnewoperator.
When two or more constructors with different argument type or numbers are created,it is known as Constructor Overloading.
When two or more functions with the same name but different type or number ofarguments are created, it is known as Function Overloading.
== operator is used to compare primitive data types. equals() method can be used to compare the value of two objects.
8/13/2019 Introduction Java 2
29/29
Basic Programming using Java OOPS in Java
== operator when used with objects returns whether both of them point to the sameobject in memory.
Polymorphism is the ability of a function to respond differently with different objects. In Static polymorphism, the decision of which function should be called is resolved at
compile time, for example, Function or Constructor Overloading.
In Dynamic Polymorphism, the decision of which function of which object should becalled is resolved at runtime.
Command line arguments make a program more generic. Reflection class can be used to inspect the data, methods and constructors of any
unknown class and then using it in your own program.