object oriented programming using core java · object oriented programming using core java java is...
TRANSCRIPT
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 1
Object oriented Programming using Core Java
Java is a simple and yet powerful object oriented programming language and it is in many respects
similar to C++. Java originated at Sun Microsystems, Inc. in 1991. It was conceived by James Gosling, Patrick
Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. It was developed to provide a
platform-independent programming language.
1.1 Platform independent
Unlike many other programming languages including C and C++ when Java is compiled, it is not
compiled into platform specific machine, rather into platform independent byte code. This byte code is
distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.
1.2 Java Virtual Machine
Java was designed with a concept of ‘write once and run everywhere’. Java Virtual Machine plays the
central role in this concept. The JVM is the environment in which Java programs execute. It is a software that is
implemented on top of real hardware and operating system. When the source code (.java files) is compiled, it is
translated into byte codes and then placed into (.class) files. The JVM executes these bytecodes. So Java byte
codes can be thought of as the machine language of the JVM. A JVM can either interpret the bytecode one
instruction at a time or the bytecode can be compiled further for the real microprocessor using what is called a
just-in-time compiler. The JVM must be implemented on a particular platform before compiled programs can
run on that platform
.
1.3 Features:
Simple
fixes some clumsy features of C++
no pointers
automatic garbage collection
rich pre-defined class library http://java.sun.com/j2se/1.4.2/docs/api/
Object oriented
focus on the data (objects) and methods manipulating the data
all functions are associated with objects
almost all data types are objects (files, strings, etc.)
potentially better code organization and reuse
Interpreted
java compiler generate byte-codes, not native machine code
the compiled byte-codes are platform-independent
java byte codes are translated on the fly to machine readable instructions in runtime (Java Virtual
Machine)
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 2
Portable
same application runs on all platforms
the sizes of the primitive data types are always the same
the libraries define portable interfaces
Reliable
extensive compile-time and runtime error checking
No pointers but real arrays. Memory corruptions or unauthorized memory accesses are impossible
automatic garbage collection tracks objects usage over time
Secure
usage in networked environments requires more security
memory allocation model is a major defense
access restrictions are forced (private, public)
Multithreaded
multiple concurrent threads of executions can run simultaneously
utilizes a sophisticated set of synchronization primitives (based on monitors and condition variables
paradigm) to achieve this
Dynamic
java is designed to adapt to evolving environment
libraries can freely add new methods and instance variables without any effect on their clients
interfaces promote flexibility and reusability in code by specifying a set of methods an object can
perform, but leaves open how these methods should be implemented
can check the class type in runtime
Automatic Garbage Collector
no need to explicitly allocate or deallocate
reclaimed by the garbage collector when it is no longer needed.
no malloc(), free(), or destructor methods.
constructors and these do allocate memory on the heap, but this is transparent to the programmer.
1.4 Object Oriented Programming Principles:
Object: An object is a software bundle of related state and behavior. Software objects are often used to model
the real-world objects that you find in everyday life.
Class: A class is a blueprint or prototype from which objects are created.
Abstract Class having Abstract methods are methods with no body specification. Subclasses must
provide the method statements for their particular meaning. If the method was one provided by the
superclass, it would require overriding in each subclass. And if one forgot to override, the applied
method statements may be inappropriate
Final Class A final class cannot be extended. This is done for reasons of security and efficiency.
Accordingly, many of the Java standard library classes are final, for example java.lang.system and
java.lang.string All methods in a final class are implicitly final.
Static Class have method which can be directly invoked no need of object.
Encapsulation: Encapsulation is the ability of an object to be a container (or capsule) for related properties (ie.
data variables) and methods (ie. functions).
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 3
Data hiding is the ability of objects to shield variables from external access. It is a useful consequence of the
encapsulation principle. Those variables marked as private can only be seen or modified through the use of
public accessor and mutator methods. This permits validity checking at run time. Access to other variables can
be allowed but with tight control on how it is done.
Inheritance & Polymorphism:
Inheritance is the capability of a class to use the properties and methods of another class while adding its own
functionality.. The generic class is known as the parent (or superclass or base class) and the specific classes as
children (or subclasses or derived classes). The concept of inheritance greatly enhances the ability to reuse code
as well as making design a much simpler and cleaner process.
Java uses the extends keyword to set the relationship between a parent class and a child class.
public class Subclass extends Superclass
When extending a class constructor you can reuse the superclass constructor and overridden superclass methods
by using the reserved word super.
The reserved word this can also be used to reference private constructors which are useful in initializing
properties.
Special Note :You cannot override final methods, methods in final classes, private methods or static methods.
Interfaces
Interfaces are similar to abstract classes but all methods are abstract and all properties are static final. Interfaces
can be inherited (ie. you can have a sub-interface). As with classes the extends keyword is used for inheritance
.Java does not allow multiple inheritance for classes (ie. a subclass being the extension of more than one
superclass). An interface is used to tie elements of several classes together. Interfaces are also used to separate
design from coding as class method headers are specified but not their bodies. This allows compilation and
parameter consistency testing prior to the coding phase. Interfaces are also used to set up unit testing
frameworks.
Polymorphism
Polymorphism is the capability of an action or method to do different things based on the object that it is acting
upon. Overloading, overriding and dynamic method binding are three types of polymorphism.
Overloaded methods are methods with the same name signature but either a different number of parameters or
different types in the parameter list. By defining a method for handling each type of parameter you control the
desired effect.
Java does not support Operator overloading.
Overridden methods are methods that are redefined within an inherited or subclass. They have the same
signature and the subclass definition is used.
Dynamic (or late) method binding is the ability of a program to resolve references to subclass methods at
runtime.
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 4
Java is not a pure Object oriented language but so called a Hybrid language.
For any language to be pure object oriented it must follow these 6 points strictly.
1) It must have full support for Encapsualtion and Abstraction
2) It must support Inheritance
3) It must support Polymorphism
4) All predefined types must be Objects
5) All user defined types must be Objects
6) Lastly all operations performed on objects must be only through methods exposed at the objects.
Now java supports 1 2 3 & 5 but fails to support 4 & 6. In java we have some predefined types as non-objects
(primitive types). Although we have wrapper classes for the same but a Pure OOL can't have anything other
than Objects strictly.
Java Overriding
If a class inherits a method from its super class, then there is a chance to override the method provided that it is
not marked final. The benefit of overriding is: ability to define a behavior that's specific to the sub class type.
Which means a subclass can implement a parent calss method based on its requirement. In object oriented
terms, overriding means to override the functionality of any existing method.
Rules for overriding:
The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in the original overridden
method in the super class.
The access level cannot be more restrictive than the overridden method's access level. For example: if
the super class method is declared public then the overridding method in the sub class cannot be either
private or public. However the access level can be less restrictive than the overridden method's access
level.
Instance methods can be overridden only if they are inherited by the subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited then it cannot be overridden.
A subclass within the same package as the instance's superclass can override any superclass method that
is not declared private or final.
A subclass in a different package can only override the non-final methods declared public or protected.
Constructors cannot be overridden.
Overriding vs. Overloading
Method overriding should not be confused with method overloading. Method overriding requires the same
method signature (name and parameters) and the same return type. Only non-final instance methods in the
superclass that are directly accessible from the subclass are eligible for overriding. Overloading occurs when the
method names are the same, but the parameter lists differ. Therefore, to overload methods, the parameters must
differ in type, order, or number. As the return type is not a part of the signature, having different return types is
not enough to overload methods. A method can be overloaded in the class it is defined in or in a subclass of its
class. Invoking an overridden method in the superclass from a subclass requires special syntax (e.g., the
keyword super). This is not necessary for invoking an overloaded method in the superclass from a subclass. If
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 5
the right kinds of arguments are passed in the method call occurring in the subclass, the overloaded method in
the superclass will be invoked.
1.4 Constructor in Java:
When you create a new instance (a new object) of a class using the new keyword, a constructor for that
class is called. Constructors are used to initialize the instance variables (fields) of an object.
Constructors are similar to methods, but with some important differences.
Constructor name is class name. A constructors must have the same name as the class its in.
Default constructor. If you don't define a constructor for a class, a default parameterless
constructor is automatically created by the compiler. The default constructor calls the default parent
constructor (super()) and initializes all instance variables to default value (zero for numeric types,
null for object references, and false for booleans).
Default constructor is created only if there are no constructors. If you define any constructor for
your class, no default constructor is automatically created.
Differences between methods and constructors.
o There is no return type given in a constructor signature (header). The value is this object
itself so there is no need to indicate a return value.
o There is no return statement in the body of the constructor.
o The first line of a constructor must either be a call on another constructor in the same class
(using this), or a call on the superclass constructor (using super). If the first line is neither of
these, the compiler automatically inserts a call to the parameterless super class constructor.
These differences in syntax between a constructor and method are sometimes hard to see when looking at the
source. It would have been better to have had a keyword to clearly mark constructors as some languages do.
1.5 Package and Access Protection
Accessed
Public Protected Package Private
same class ?
Yes Yes Yes Yes
From a non subclass in
the same package ? Yes Yes Yes No
From a non subclass
outside the package? Yes No No No
From a subclass
in the same package? Yes Yes Yes No
From a subclass
outside the package ? Yes Yes No No
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 6
1.6 Attribute modifiers in Java:
1.7Syntax for a standalone application in Java
class <classname>
{
public static void main(String args[])
{
statements;
————————;
————————;
}
}
Steps to run the above application:
1. Type the program in the DOS editor or notepad. Save the file with a .java extension.
2. The file name should be the same as the class, which has the main method.
3. To compile the program, using javac compiler, type the following on the command line:
Syntax: javac <filename.java>
Modifier
Acts on Description
abstract
Class Class Contains abstract methods. Cannot
Interface All interfaces are implicitly abstract. The modifier is optional.
Method
Method without a body.
Signature is followed by a
Semicolon. The class must also be abstract.
final
Class Cannot be subclassed.
Method Cannot be overridden.
Variable Value cannot be changed (Constant)
native Method
Implemented in a language
other than Java like C,C++,
assembly etc. Methods do not have bodies.
static
Method
Class method. It cannot refer to nonstatic variables and methods of
the class. Static methods are implicitly final and invoked
through the class name.
Variable
Class variable. It has only onecopy regardless of how many
instances are created. Accessed only through the class name.
synchronized Method
A class which has a synchronized method automatically acts as a
lock. Only one synchronized method can run for each class.
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 7
Example: javac abc.java
4. After compilation, run the program using the Java interpreter.
Syntax: java <filaname> (without the .java extension)
Example: java abc
5. The program output will be displayed on the command line
Setting Path on Windows
For Windows XP:
1. Start -> Control Panel -> System -> Advanced
2. Click on Environment Variables, under System Variables, find PATH, and click on it.
3. In the Edit windows, modify PATH by adding the location of the class to the value for
PATH. If you do not have the item PATH, you may select to add a new variable and add
PATH as the name and the location of the class as the value.
4. Close the window.
5. Reopen Command prompt window, and run your java code.
1.8 Eclipse Overview
Most people know Eclipse as an integrated development environment (IDE) for Java. Eclipse is created
by an open source community and is used in several different areas, e.g. as IDE for Java or for Android or as
a platform to develop Eclipse RCP applications, etc.. The usage of Eclipse as a Java development
environment will be described in this tutorial.
To start Eclipse double-click on the file "eclipse.exe" (Microsoft Windows) or eclipse (Linux / Mac) in the
directory you unpacked Eclipse. The system will prompt you for a workspace. The workspace is the place
there you store your Java projects. Select an empty directory and press Ok.
Eclipse will start and show the Welcome page. Close the welcome page by press the "X" besides the
"Welcome".
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 8
Eclipse UI Overview Eclipse provides perspectives, views and editors. Views and editors are grouped into
perspectives. All projects are located in a workspace.
Workspace The workspace is the physical location (file path) you are working in. You can choose the
workspace during startup of eclipse or via the menu (File-> Switch Workspace-> Others). All your projects,
sources files, images and other artifacts will be stored and saved in your workspace.
You can predefine the workspace via the startup parameter -data path_to_workspace, e.g. "c:\eclipse.exe -
data "c:\temp" Please note that you have to put the path name into brackets. To see the current workspace
directory in the title of Eclipse use -showLocation as additional parameter.
Perspective A perspective is a visual container for a set of views and editors. You can change the layout
within a perspective (close / open views, editors, change the size, change the position, etc.). Eclipse allow
you to switch to another perspective via the menu Window->Open Perspective -> Other. For Java
development you usually use the "Java Perspective".
Tip
A common problem is that you closed a view and don't know how to re-open this view. You can reset a
perspective it to it original state via the menu "Window" -> "Reset Perspective".
Views and Editors A view is typically used to navigate a hierarchy of information or to open an editor.
Changes in a view are directly applied to the underlying data structure. Editors are used to modify elements.
Editors can have code completion, undo / redo, etc. To apply the changes in an editor to the underlying
resources, e.g. Java source file, you usually have to save.
1.9 Create your first Java program
The following will describe how to create a minimal Java program using Eclipse. It will be the classical "Hello
World" program. Our program will write "Hello Eclipse!" to the console.
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 9
Create project
Select from the menu File -> New-> Java project. Maintain "de.vogella.eclipse.ide.first" as the project name.
Select "Create separate source and output folders".
Press finish to create the project. A new project is created and displayed as a folder. Open the folder
"de.vogella.eclipse.ide.first"
Create package
Create now a package. A good convention is to use the same name for the top package as the project. Create
therefore the package "de.vogella.eclipse.ide.first".
Select the folder src, right mouse click on it and select New -> Package.
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 10
Create Java class
Right click on your package and select New -> Class
Create MyFirstClass, select the flag "public static void main (String[] args)"
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 11
Maintain the following code.
package de.vogella.eclipse.ide.first;
public class MyFirstClass {
public static void main(String[] args) {
System.out.println("Hello Eclipse!");
}
}
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 12
Run your project in Eclipse
Now run your code. Right click on your Java class and select Run-as-> Java application
Finished! You should see the output in the console.
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 13
1.10 Primitive Data Types
Data Type Size Default
Min Value Max
Value
byte
(Signed
integer)
8 bits 0 -128+127
short
(Signed
integer
16 bits 0 -32,768+32,767
int
(Signed
integer)
32 bits 0
-
2,147,483,648+2,147,48
3,647
long
(Signed
Integer)
64 bits 0
-9, 223, 372,036,854,
775,808,
+9,223,372,036 854,
775, 807
float
(IEEE 754
floating-point)
32 bits 0.0 1.4E-45
3.4028235E38
Double
(IEEE 754
floating-point)
64 bits 0.0
4.9E-324
1.7976931348623157E3
08
char
(Unicode
Character)
16 bit \u0000 \u0000
\uFFFF
Boolean 1 bit false _
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 14
Variable Declaration:
<datatype> <variable name>
Example: int num1;
Variable Initialization:
<datatype> <variable name> = value
Example: double num2 = 3.1419;
1.11 Summary of Operators
The following quick reference summarizes the operators supported by the Java programming language.
Simple Assignment Operator
= Simple assignment operator
Arithmetic Operators
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Unary Operators
+ Unary plus operator; indicates positive value (numbers are positive
without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical compliment operator; inverts the value of a boolean
Equality and Relational Operators
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
Conditional Operators
&& Conditional-AND
|| Conditional-OR
?: Ternary (shorthand for if-then-else statement)
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 15
Type Comparison Operator
instanceof Compares an object to a specified type
Bitwise and Bit Shift Operators
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
1.12 Java Comments
1.13 Control Statements
The control statement is used to control the flow of execution of the program. This execution order
depends on the supplied data values and the conditional logic. Java contains the following types of control
statements:
1- Selection Statements
2- Repetition Statements
3- Branching Statements
Selection statements:
1. If Statement: This is a control statement to execute a single statement or a block of code, when the
given condition is true and if it is false then it skips if block and rest code of program is executed.
Syntax:
if(conditional_expression){
<statements>;
...;
...;
}
2. If-else Statement: The "if-else" statement is an extension of if statement that provides another option
when 'if' statement evaluates to "false" i.e. else block is executed if "if" statement is false.
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 16
Syntax:
if (conditional_expression){
<statements>;
...;
...;
}
else{
<statements>;
....;
....;
}
3. Switch Statement: This is an easier implementation to the if-else statements. The keyword "switch"
is followed by an expression that should evaluates to byte, short, char or int primitive data types, only. In
a switch block there can be one or more labeled cases.. The switch expression is matched with each case
label. Only the matched case is executed, if no case matches then the default statement (if present) is
executed.
Syntax:
switch(control_expression){
case expression 1:
<statement>;
case expression 2:
<statement>;
. ..
case expression n:
<statement>;
default:
<statement>;
}//end switch
Repetition Statements:
1. While loop statements: This is a looping or repeating statement. It executes a block of code or
statements till the given condition are true. The expression must be evaluated to a boolean value.
It continues testing the condition and executes the block of code. When the expression results to
false control comes out of loop.
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 17
1. Syntax:
while(expression){
<statement>;
...;
...;
}
2. do-while loop statements:
This is another looping statement that tests the given condition past so you can say that the do-
while looping statement is a past-test loop statement. First the do block statements are executed
then the condition given in while statement is checked. So in this case, even the condition is false
in the first attempt, do block of code is executed at least once.
Syntax:
do{
<statement>;
...;
...;
}while (expression);
3. for loop statements: This is also a loop statement that provides a compact way to iterate over a
range of values. From a user point of view, this is reliable because it executes the statements
within this block repeatedly till the specified conditions is true .
Syntax:
for (initialization; condition; increment or decrement){
<statement>;
...;
...;
}
initialization: The loop is started with the value specified.
condition: It evaluates to either 'true' or 'false'. If it is false then the loop is terminated.
increment or decrement: After each iteration, value increments or decrements.
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 18
Branching Statements:
1. Break statements: The break statement is a branching statement that contains two forms:
labeled and unlabeled. The break statement is used for breaking the execution of a loop
(while, do-while and for) . It also terminates the switch statements.
Syntax:
break; // breaks the innermost loop or switch statement.
break label; // breaks the outermost loop in a series of nested loops.
2. Continue statements: This is a branching statement that is used in the looping statements
(while, do-while and for) to skip the current iteration of the loop and resume the next
iteration.
Syntax:
continue;
3. Return statements: It is a special branching statement that transfers the control to the
caller of the method. This statement is used to return a value to the caller method and
terminates execution of method. This has two forms: one that returns a value and the other
that can not return. The returned value type must match the return type of method.
Syntax:
return;
return values;
return; //This returns nothing. So this can be used when method is declared with
void return type.
return expression; //It returns the value evaluated from the expression.
1.14 Equals () and Hashcode () methods
The Java super class java.lang.Object has two very important methods defined in it. They are -
public boolean equals(Object obj) public int hashCode()
Normally, most Java objects provide a built-in equals() and Hashcode() based on the object's identity; so
each new() object will be different from all others.
This is generally what you want in ordinary Java programming. And if all your objects are in memory,
this is a fine model. Hibernate's whole job, of course, is to move your objects out of memory. But
Hibernate works hard to prevent you from having to worry about this.
Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(),
and then save it into a session, Hibernate now knows that whenever you query for an object and find that
particular object, Hibernate should return you that instance of the object. And Hibernate will do just
that.
Software Development Tools Laboratory
Dept. of Comp. Engg. Matoshri College of Engineering and Research Center, Nashik-422105 Page 19
However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that
you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to
know about those objects. So if you open another session and query for "the same" object, Hibernate
will return you a new instance. Hence, if you keep collections of objects around between sessions, you
will start to experience odd behavior (duplicate objects in collections, mainly).
The general contract is: if you want to store an object in a List, Map or a Set then it is a requirement that
equals and Hashcode are implemented so they obey the standard practice.
public boolean equals(Object obj)
This method checks if some other object passed to it as an argument is equal to the object on which this
method is invoked..
public int hashCode()
This method returns the hash code value for the object on which this method is invoked. This method
returns the hash code value as an integer and is supported for the benefit of hashing based collection
classes such as Hashtable, HashMap, HashSet etc. This method must be overridden in every class that
overrides the equals method. It indicates that hashCode is the native implementation which provides
the memory address to a certain extent. However it is possible to override the hashCode method in your
implementation class.