Oop Chapter1
Oop Chapter1
Oop Chapter1
Chapter1
Java Fundamentals and OOP overview.
introduction to java
Java is a programming language
Invented by James Gosling at Sun
Microsystems in California. The
language was first called Oak,
named after the oak tree outside
of Gosling’s office, but the name
was already taken, so the team
renamed it Java.
…Introduction to java
Why Java?
It’s the current “hot” language
It’s almost entirely object-oriented
It has a vast library of predefined
objects and operations
It’s more platform independent
◦ this makes it great for Web
programming
It’s more secure
It isn’t C++
… introduction to java
Java has some interesting
features:
◦ automatic type checking,
◦ automatic garbage collection,
◦ simplifies pointers; no directly
accessible pointer to memory,
◦ simplified network access,
◦ multi-threading!
Characteristics of Java
myprog.c myprog.exe
gcc machine code
C source code
OS/Hardware
Platform Independent
myprog.java myprog.class
Java source javac bytecode
code
JVM
OS/Hardware
Why java is platform
independent
Javais independent only for one
reason:
◦ Only depends on the Java Virtual
Machine (JVM),
◦ code is compiled to bytecode, which is
interpreted by the resident JVM,
◦ JIT (just in time) compilers attempt to
increase speed.
Java Advantages
Java Advantages
Portable - Write Once, Run Anywhere
Security has been well thought
through
Robust memory management
Designed for network programming
Multi-threaded (multiple simultaneous
tasks)
Dynamic & extensible (loads of
libraries)
◦ Classes stored in separate files
Java Programming
Environment
Two Programming Environments for java.
1/ IDE
Integrated Development
Environment.
example: Netbeans.
2/CLE
Command Line Environment.
using :cmd
…Java Programming
Environment
Steps to run and compile in CLE.
1. Type the source code in a text editor such as
notepad.
2. Save it in the directory containing the Java compiler
files (Java Development Kit-JDK) /state the path of
JDK inside Environment variables.filename.java
(The name is important!!!).
3. You must have Java installed on your machine. Go
into the directory containing Test.java, in cmd
type:Javac filename.java
4. This compiles it producing a class file,
filename.class
5. Run filename.class by typing the command: java
filename
Comments in java
/* This kind of comment can span multiple
lines */
// This kind is to the end of the line
/**
* This kind of comment is a special
* ‘javadoc’ style comment
*/
Data types
Primitive Types and
Variables
boolean, char, byte, short, int, long, float,
double etc.
These basic (or primitive) types are the only
types that are not objects (due to performance
issues).
This means that you don’t use the new
operator to create a primitive variable.
Declaring primitive variables:
float initVal;
int retVal, index = 2;
double gamma = 1.2, brightness
boolean valueOk = false;
Initialisation
Ifno value is assigned prior to use,
then the compiler will give an error
Java sets primitive variables to zero or
false in the case of a boolean variable
All object references are initially set to
null
An array of anything is an object
◦ Set to null on declaration
◦ Elements to zero false or null on
creation
Declarations
int index = 1.2; // compiler error
boolean retOk = 1; // compiler error
double fiveFourths = 5 / 4; // no error!
float ratio = 5.8f; // correct
double fiveFourths = 5.0 / 4.0; // correct
Assignment
All Java assignments are right associative
int a = 1, b = 2, c = 5
a=b=c
System.out.print(
“a= “ + a + “b= “ + b + “c= “ + c)
== Equal (careful)
!= Not equal
>= Greater than or equal
<= Less than or equal
> Greater than
< Less than
If… else
The if … else statement evaluates an
expression and performs one action if that
evaluation is true or a different action if it is
false.
if (x != oldx) {
System.out.print(“x was changed”);
}
else {
System.out.print(“x is unchanged”);
}
Nested if … else
while(response == 1) {
System.out.print( “ID =” + userID[n]);
n++;
response = readInt( “Enter “);
}
do {… } while loops
do {
System.out.print( “ID =” + userID[n] );
n++;
response = readInt( “Enter ” );
}while (response == 1);
Break
A a = new A(); a b
A b = new A(); Output: 0 0
System.out.println(b.x_); y y
a.x_ = 5;
System.out.println(b.x_);
1
A.x_ = 10; 5 1
System.out.println(b.x_); 10 A.x_
Static Method
Static member method/function
◦ Static member function can access only
static members
◦ Static member function can be called
Class TeaPot {
without an instance.
private static int numOfTP = 0;
private Color myColor_;
public TeaPot(Color c) {
myColor_ = c;
numOfTP++;
}
public static int howManyTeaPots()
{ return numOfTP; }
// error :
public static Color getColor()
{ return myColor_; }
}
Java program layout
//convention of a class
{
}
Member methods : instant method, main method…
Instance variable: a variable which all object of a class can
use
The structure of a method includes
a method signature and a code
body
[access modifier] return type method
name (list of arguments)
{
statements, including local variable
declarations
}
main() method Inside the class ,outside
other instance methods.
Example
class Circle
{
float rad;
int xCoord, yCoord;
void showArea(){
float area = Math.PI*rad*rad;
System.out.println(“The area is:” + area);
}
void showCircumference()
{
float circum=2* Math.PI*rad;
System.out.println(“The circumference is:”+circum);
}
}
…try
Identify class, field and method of the
previous example?
Object ?
Object
An object is an instance of a class.
Creating an object is a two-step process.
Example
Circle c1 = new Circle();
c1.rad = 2.3;
c1.showArea();
c1.showCircumference();
…object and class
In short
Class is a type.
PreciseClock dawn;
dawn = new Clock(3,40);//ERROR
Abstract Classes
Abstract classes are only used as super classes
Classes are declared as abstract classes only if
they will never be instantiated
Abstract classes contain usually one or more
abstract methods
Example:
public abstract class Mouse implements
Direction {
…
abstract void makeMove( );
}
Abstract Methods
Abstract methods have no body at all and just
have their headers declared
The only way to use an abstract class is to create
a subclass that implements each abstract method
Concrete classes are classes that implement each
abstract method in their superclasses
Example:
abstract void makeMove( );
Method is abstract if :
1/Declared as abstract.
2/Declared inside an interface.
abstract Vs final
◦ final ◦ abstract
Final class must not Abstract class must
be be subclassed.
subclassed(prevent (prevents
s inheritance). instantiation)
try { … }
catch (ArrayIndexOutOfBounds ae) { … }
catch (Exception e) { … }
Checked and Unchecked
Exceptions
Unchecked exceptionsdo not have to be
handled (e.g. ArrayIndexOutOfBounds or
NullPointer)
Checked exceptionsmust be handled when
they occur
Most programmer defined exceptions are
for checked exceptions
Programmer Defined
Exceptions
class InvalidIntegerException extends
Exception {
InvalidIntegerException (String s) {
super(s);
}
InvalidIntegerException () {
this(“ ”);
}
}
Method Header Throws
Clauses
void m() {
…
try { … N() … }
catch (InvalidIntegerException iie) { … }
…
}
void n() throws InvalidIntegerException {
… p() …
}
void p() throws InvalidIntegerException {
… throw new InvalidIntegerException(); …
}
Interface
An interface is basically a kind of class. Like
classes, interfaces contain methods and
variables but with a major difference.
The difference is that interfaces define only
abstract methods and final fields.
Creating an interface
interface InterfaceName
{
Variable declaration;
Method declaration;
}
…Interface
variable declaration
[static] [final] type va_Name =
<value>;
method declaration
[public ]ret_Type
methodName(arg_List);
…interface
Example:
//shape.java
interface Shape
{
final double PI = 3.14;
public abstract double
Volume();
public abstract double
getName();
}
…Interface
All the methods are defined as
abstract (method with no
implementation).
Interface shall also be saved in
Java file using .java extension.
If there are attributes in an
interface they should be static
final.
…Interface
Use implements keyword to
implement the abstract method of
the interface.
}
An interface can be sub interfaced from another
interface.
Examples
Area inter face
PI
compute(int,int)
An interface cannot be
If the class is the abstract instantiated.
class it cannot instantiated
A class implements a inter
face must implement all
A sub class of abstract class
method of the interface
must implement all the
inherited abstract method.
An interface has no
Class defines its own constructor
constructor
}
Inner classes
Class inside another class.
Inner class can be hidden from other class in the same
package.
Inner class are members of outer class.
Declared with any visibility.
Can access all members including private members.
but outer class access all non private member of inner class.
Use outer class reference with each inner class.
Synax:
class OuterClass
{
class InnerClass
{
}
}
Packages
A package is a structure for containing a
group of related classes. Package is both a
namespace management as well as
visibility control.
a group of classes
A package name implies the directory
structure where files reside.
Resolves name conflicts for classes.
Package declaration
import java.util.date;
java.util.Date d = new
Import java.awt.*;
java.util.Date();
…
java.awt.Point p =new
Date d = new Date();
java.awt.Point(1,2);
Point p = new Point(1,2);
java.awt.Button b =new
java.awt.Button(); Button b = new Button();
Creating Your Own
Packages
Each package class must be stored in a file
in an appropriately named directory
The source code file for each package
class must contain a package statement as
its first non-commented statement
package package_name;
Several packages can be stored in the
same directory
Classes in different directories cannot be
part of the same package
Visibility Rules and
Packages
Instance variables declared as public or private
have the same visibility to classes in other
packages
Instance variables without explicitly declared
visibility have package visibility
Instance variables with package visibility are
only visible to methods defined in classes
belonging to the same package
Similarly for static variables, instance methods,
and static methods having package visibility
Classes not explicitly declared public are not
visible outside the package
End