Oop Chapter1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 123

Advanced Programming with java

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

1. Java is Platform Independent


•Platform independence is another way of saying that
Java is architecture neutral. This basically means
that Java programs don’t care what system they are
running on.
2. Java is Object-Oriented
•It organizes a program as a set of components called
objects. These objects exist independently of each
other, and they have rules for communicating with
other objects and for telling those objects to do
things.
3. Java is Easy to Learn
•Java was intended to be easier to write, compile,
debug, and learn. Much of its syntax and object
oriented structure comes straight from C++
Platform Dependent

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)

 What is the value of a, b & c


 Done right to left: a = (b = c);
Basic Mathematical
Operators
* / % + - are the mathematical operators
 * / % have a higher precedence than + or -
double myVal = a + b % d – c * d / b;
 Is the same as:
double myVal = (a + (b % d)) –
((c * d) / b);
Statements & Blocks

A simple statement is a command


terminated by a semi-colon:
name = “Fred”;
 A block is a compound statement enclosed
in curly brackets:
{
name1 = “Fred”; name2 = “Bill”;
}
 Blocks may contain other blocks
Flow of Control
Java executes one statement after the
other in the order they are written
Many Java statements are flow control
statements:
Alternation: if, if else, switch
Looping: for, while, do while
Escapes: break, continue, return
If – The Conditional
Statement
 The if statement evaluates an expression
and if that evaluation is true then the
specified action is taken
if ( x < 10 ) x = 10;
 If the value of x is less than 10, make x
equal to 10
 It could have been written:
if ( x < 10 )
x = 10;
 Or, alternatively:
if ( x < 10 ) { x = 10; }
Relational Operators

== 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

if ( myVal > 100 ) {


if ( remainderOn == true) {
myVal = mVal % 100;
}
else {
myVal = myVal / 100.0;
}
}
else
{
System.out.print(“myVal is in range”);
}
else if
 Useful for choosing between alternatives:
if ( n == 1 ) {
// execute code block #1
}
else if ( j == 2 ) {
// execute code block #2
}
else {
// if all previous tests have failed, execute
code block #3
}
A Warning…
WRONG! CORRECT!
if( i == j ) if( i == j ) {
if ( j == k )
if ( j == k )
System.out.print(
System.out.print( “i equals k”);
“i equals }
k”); else
else
System.out.print( System.out.print(“
i is not equal to
“i is not equal
j”); // Correct!
to j”);
The switch Statement
switch ( n ) {
case 1:
// execute code block #1
break;
case 2:
// execute code block #2
break;
default:
// if all previous tests fail
then //execute code block #4
break;
}
The for loop
 Loop n times
for ( i = 0; i < n; n++ ) {
// this code body will execute n times
// ifrom 0 to n-1
}
 Nested for:
for ( j = 0; j < 10; j++ ) {
for ( i = 0; i < 20; i++ ){
// this code body will execute 200
times
}
}
while loops

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 break statement causes an exit


from the innermost containing while,
do, for or switch statement.
for ( int i = 0; i < maxID, i++ ) {
if ( userID[i] == targetID ) {
index = i;
break;
}
} // program jumps here after break
Continue
 Can only be used with while, do or for.
 The continue statement causes the
innermost loop to start the next iteration
immediately
for ( int i = 0; i < maxID; i++ ) {
if ( userID[i] != -1 ) continue;
System.out.print( “UserID ” + i + “ :” +
userID);
}
Arrays
 An array is a list of similar things
 An array has a fixed:
◦ name
◦ type
◦ length
 These must be declared when the array is
created.
 Arrays sizes cannot be changed during the
execution of the code
myArray 3 6 3 1 6 3 4 1
=
0 1 2 3 4 5 6 7

myArray has room for 8 elements


 the elements are accessed by their index
 in Java, array indices start at 0
Declaring Arrays
int myArray[];
declares myArray to be an array of
integers
myArray = new int[8];
sets up 8 integer-sized spaces in
memory, labelled myArray[0] to
myArray[7]
int myArray[] = new int[8];
combines the two statements in one
line
Assigning Values
 referto the array elements by index to store
values in them.
myArray[0] = 3;
myArray[1] = 6;
myArray[2] = 3; ...
 can create and initialise in one step:

int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};


Iterating Through Arrays
for loops are useful when dealing with arrays:

for (int i = 0; i <


myArray.length; i++) {
myArray[i] = getsomevalue();
}
Arrays of Objects
 So far we have looked at an array of
primitive types.
◦ integers
◦ could also use doubles, floats, characters…
 Often want to have an array of objects
◦ Students, Books, Loans ……
 Need to follow 3 steps.
Declaring the Array
1. Declare the array
private Student studentList[];
◦ this declares studentList
2 .Create the array
studentList = new Student[10];
◦ this sets up 10 spaces in memory
that can hold references to Student
objects
3. Create Student objects and add them to
the array: studentList[0] = new
Student("Cathy", "Computing");
Static Variables
Member data - Same data is used for
all the instances (objects) of some Class.
Assignment performed
Class A {
on the first access to the
public int y = 0;
Class.
public static int x_ =
Only one instance of ‘x’
1;
exists in memory
};

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

A typical Java file looks like:


import packages;
public class ClassName {
// object definitions go here
//attributes and methods also here
. . .
}
This must be in a file named ClassName.java !
Name conventions

Class names begin with a capital


letter.
All other names begin with a
lowercase letter.
Subsequent words are capitalized.
Underscores are not used in
names.
These are very strong conventions!
!!!Java is case-sensitive!!!
Simple Input/output
To display text in the screen use:
System.out.println(“text going to be
displayed”);//ln is
//used to display in new
line
To enter the inputs from the keyboard:
Scanner <scanner name> = new Scanner(System.in);
<scanner name>.nextLine(); // to accept input as String
<scanner name>.nextOtherType(); //to accept input as
speacified type
example <scanner name>.nextInt(); //accepts
integer
Examples
Hello.java
class Hello {
public static void main(String[] args) {
System.out.println(“Hello World !!!”);
}
}
OOP overview
oop
Object oriented
 The way to organize a program as a set
of component called object.
It is a power full way of organizing and
developing a software.
one characteristics of java.
Object and class:
class?
Object?
Class
A class is a logical framework or blue print
or template of an object.
A class is a programmer defined data type.
A class has :-
 state (field) and
 behavior (method)
Fields: say what a class is(Things an object
knows about itself).

Hold data values.


Methods: say what a class does(Things an
object can do).
Definition and declaration of a class
Syntax:
class ClassName
{
//member attributes (instance /classvariables)
//member Methods
}
Example: Public class Student//consider the naming

//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.

Creating a reference variable


Syntax:
<class idn><ref. idn>;
eg. Circle c1;
Setting or assigning the reference with the
newly created object.
Syntax:
<ref. idn> = new <class idn>(…);
c1 = new Circle();
The two steps can be done in a single
statement
Circle c2 = new Circle();
Accessing members of an
Object
To access members of an object we use ‘.’
(dot) operator together with the reference
to an object.
<ref. idn>.<member>;

Example
Circle c1 = new Circle();
c1.rad = 2.3;
c1.showArea();
c1.showCircumference();
…object and class
In short
Class is a type.

Object is instance of a type (class).


Exercise
Write a java programs for Student class
which consists of
name ,idno, sex as attribute(feilds).
showStudentInfo() as Methods.
(hint store the value from the user to the
instance of the class the fields are
accessible for both main method and
instance method)
Sample output :
Enter Stud name:Abebe
Enter Stud Id no:0000
Enter Stud Sex:M
Student Information: Name : Abebe ID: 0000 sex:M
Constructor ?
Constructor
Special type of method invoked when you instantiate a
class.
Constructors are used to initialize the instance variables
(fields) of an object.
Its called when the object is created.
Constructors are similar to methods, but with some
important differences.
 Constructor name is class name.
 Default constructor is created by compiler If you don't
define a constructor for a class.
 no return type there fore no return statement even no
void.
Syntax public ClassName(arguments)
{
Abstraction
Abstraction is the thought process where
in ideas are separated from objects.
We form concepts of everyday objects and
events by a process of abstraction where we
remove unimportant details and concentrate
on the essential attributes of the thing.
Roughly speaking, abstraction can be either
that of control or data.
Control abstraction is the abstraction of actions
while data abstraction is that of data
Abstraction is just a fancy name for
encapsulating the data and method.
Inheritance
A feature that allow us to drive class from
another class.
Allows programmers to customize a class
for a specific purpose, without actually
modifying the original class (the
superclass)
The derived class (subclass) is allowed to
add methods or redefine them
The subclass can add variables, but cannot
redefine them
…Inheritance
Two classes involved in inheritance:
1.Sub class : Inherits.
2.Super class: Allows another class to
inherit.
Inheritance Example
Class C is a subclass of class B (its
superclass) if its declaration has the form
class C extends B {

}
The subclass is a specialization of the
superclass
The super class is a generalization of the
subclass
Inheritance and Messages
When C is a subclass of B
C objects can respond to all messages that
B objects can respond to
In general C objects can be used whenever
B objects can be used
It is possible the a subclass of B may have
methods and variables that have not been
defined in B
It is the case B objects may not always be
used in place of C objects
Inheritance Hierarchy
A class may have several subclasses and each
subclass may have subclasses of its own
The collection of all subclasses descended
from a common ancestor is called an
inheritance hierarchy
The classes that appear below a given class in
the inheritance hierarchy are its descendants
The classes that appear above a given class in
the inheritance hierarchy are its ancestors
Inheritance and Visibility
Rules
Private variables and methods are not visible to
subclasses or clients.(accessible only from with in this class)
Public variables and methods are visible to all
subclasses and clients.(accessible from any where)
Variables and methods with package visibility
are only visible to subclasses and clients
defined in the same package as the class.(accessible
from the same package)

A variable or method declared with the


protected visibility modifier can only be
referenced by subclasses of the class and no
other classes.(accessible from any descendents in the same package)
Constructors and
inheritance
The general rule is that when a subclass is
created Java will call the superclass
constructor first and then call the subclass
constructors in the order determined by
the inheritance hierarchy
If a superclass does not have a default
constructor with no arguments, the
subclass must explicitly call the superclass
constructor with the appropriate
arguments
Using super( ) Call
Constructor
The call to super must be the first
statement in the subclass constructor
Example:
class C extends B {

public C ( … ) {
super( B’s constructor arguments );

}

Overriding Vs Overloading
A method is overloaded if it has multiple
definitions that are distinguished from one another
by having different numbers or types of arguments
A method is overridden when a subclass gives a
different definition of the method with the same
number and types of arguments.
The method has the same
 signature
 Name with method defined in a super
class.
 return type
 Parameter list
Calling Overridden
Superclass Methods from
Subclassess
The following code generates an infinite loop
because toString( ) is interpreted as this.toString( )
public String toString() {
String result = toString();// b/c it consider as
recursive call
return (result + “:” + second);
}
To make a call toString in the superclass instead

public String toString() {


String result = super.toString();
return (result + “:” + second);
}
Creation of Subclass
Instances
Assuming that PreciseClock is a subclass of
the Clock class, the following is legal
Clock dawn;
dawn = new PreciseClock(3,45,30);
The instance variable dawn will respond to all
PreciseClock messages
It is not legal to write this since Clock objects
cannot respond to all PreciseClock messages

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)

A final method must An abstract method


not be overridden must be overridden.
Polymorphism
“a method the same as another in spelling
but with different behavior.”
Generally, polymorphism refers to the
ability to appear in many forms.
The computer differentiates between (or
among) methods depending on either the
method signature (after compile) or the
object reference (at run time).
Static and Dynamic
Binding
Static Binding
Determining which method will be invoked
to respond to a message at compile time
Dynamic Binding
Determining which method will be invoked
to respond to a message at run time
Required when method definitions are
overridden in subclasses, since type of the
receiver class may not be known until run
time
early-binding (compile time/static
binding) polymorphism
The computer knows after the compile to
the byte code which methods it will
execute.
That is, after the compile process when
the code is now in byte-code form, the
computer will “know” which methods it will
execute.
compile-time polymorphism is achieved
with overloaded methods
Static poly… Example

A Java program written to demonstrate public class DemoClass


compile-time
{
// polymorphism using overloaded
methods public intadd(intx, inty)
public class OverLoaded {
{ return x + y;
public static void main(String[] args) }// end add(int, int)
{ public intadd(intx,inty,intz)
DemoClass obj= new DemoClass(); {
System.out.println(obj.add(2,5)); // int,
int
return x + y + z;
System.out.println(obj.add(2, 5, 9)); // }// end add(int, int, int)
int, int, int public intadd(double pi, intx)
System.out.println(obj.add(3.19, 10)); // {
double, int
return (int)pi + x;
} // end main
}// end add(double, int)
}// end OverLoaded
}// end DemoClass
Late-binding
(dynamic/run-time)
polymorphism
The computer does not know at compile time
which of the methods are to be executed.
It will not know that until “run time.”
Run-time polymorphism is achieved through
overridden methods.
Run-time polymorphism comes in three different
forms:
Run-time polymorphism with abstract base
classes
Run-time polymorphism with interfaces
Run-time polymorphism with concrete base
class
Run-time poly…Concrete:
Example
Given the parent class Person and the
child class Student, we add another
subclass of Person which is Employee.
•Below is the class hierarchy
Run-time poly…
Concrete :Example
public class Person{ class Employee extends Person{
public String name; public String getName(){

public String getName(){ System.out.println(“Employee


Name:” + name);
System.out.println(“Person name return name;
= “ + name);
}}
return name;
class Demo
}} {
class Student extends public static void main( String[] args )
Person{ {
public String getName(){ Student studentObject = new
Student();
System.out.println(“Student
Name:” + name); studentObject.name = “Abebe”;
Employee employeeObject = new
return name;
Employee();
} employeeObject.name = “Kebede”;
} Person ref = studentObject;
System.out.println(ref.getName());
ref = employeeObject;
Run-time poly…:Example:
abstract
public interface Shape
{
public double area(int,int);
} // end shape
public class Triangle implements Shape
{
public double area(intb, inth)
{
return 0.5 * b * h;
}
}// end Triangle.
public class Rectangle implements Shape
{
public double area(intb, inth)
{
return b * h;
} }// end Rectangle
Benefits of
Polymorphism
Simplicity
If you need to write code that deals with a family of
types, the code can ignore type-specific details and
just interact with the base type of the family
Even though the code thinks it is using an object of
the base class, the object's class could actually be
the base class or any one of its subclasses
This makes your code easier for you to write and
easier for others to understand
Extensibility
Other subclasses could be added later to the family
of types, and objects of those new subclasses would
also work with the existing code
Exceptions
Exceptions are things that are not
supposed to occur
Some exceptions (like division by zero) are
avoidable through careful programming
Some exceptions (like losing a network
connection) are not avoidable or
predictable
Java allows programmers to define their
own means of handling exceptions when
they occur
Exception-Handling
Mechanism
Mechanism for creating special exception
classes (whose instances are called
exception objects)
The statement throw eis used to signal the
occurrence of an exception and return
control to the calling method and erefers
to an exception object
The statement try/catchallows the calling
method to “catch” the “thrown” exception
object and take appropriate actions
Exception Example
The body of a method may call other methods as
well as doing its own calculations
Here the body of m will execute unless an out-of
bounds exception occurs
void m (){
try {
… body of m …
}
catch (ArrayIndexOutOfBoundsException ae) {
… code to recover from error …
}
}
Control Flow and
Exceptions
When exception is thrown control returns
through the methods called in reverse
calling order until a try statement is found
with a catch block for the exception
It is possible for a catch statement to defer
handling of an exception by including a
throw statement of its own
Exception in p Handled by
n
void m() {

try { … n() … }
catch (ArrayIndexOutOfBounds ae) { … }

}
void n() {

try { … p() … }
catch (ArrayIndexOutOfBounds ae) { … }

}
void p() { … A[I] … }
Deferring Exception
Handling to n’s Calling
Method
void n() {

try { … p() … }
catch (ArrayIndexOutOfBounds ae) {
if ( able to handle error )
handle it
}
else throw ae;
}

}
finally Clause
When exception is thrown control is
transferred to method containing the catch
block to handle the exception
Control does not return to procedure in
which the exception was thrown unless it
contains a finally clause
The finally clause can be used to clean up
the programming environment after the
exceptions has been handled
Finally clause Example
void n() {

try { … open window… p() … }
catch (SomeException se) { … }
finally { … close window… }

}
void p() { … throw se … }
Handling Multiple
Exceptions
void m() {

try { … n() … }
catch (ArrayIndexOutOfBounds ae) { … }
catch (NullPointerException npe) { … }

}
void n() {
try {… A[I] … anObject.v … }
finally { … }

}
Exception Hierarchy
Try can catch any exception using the
following code
try { … }
catch (Exception e) {
… handle any type of exception…
}
You must be careful because Java executes
the first catch statement it finds that
capable of handling the exception
Which handler is
executed?
In this example the second handler is never
executed
try { … }
catch (Exception e) { … }
catch (ArrayIndexOutOfBounds ae) { … }
In this example the second handler is only
executed if there is no array subscript error

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.

public class Point extends Object implements Shape


{

// body of point class


//class implements an interface if it supplies code for
all method of that interface

}
An interface can be sub interfaced from another
interface.
Examples
Area inter face
PI
compute(int,int)

Circle and rectangle implements this


interface.
Class Vs Interface
Similarities
 Class  Interface
Provides secondary data Provides secondary data type
type for the object of the for the object of the class
subclass implement it

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.

Class extend another class Interface extend another


interface
Difference
Class Interface

Class can extend only one Class can implement any


class number of interface

An interface has no
Class defines its own constructor
constructor

If class is abstract All methods are abstract.


one/more method is
abstract
Advantage
Provides standard set of methods for a group of class

Therefore interface used as protocol


…interface
Interface is extends another interface.
use extends keyword.
Syntax:
interface SubInterface extends
SuperInterface
{
//body of sub interface

}
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

There is zero or one package declaration


per class.
Must be first non-comment statement.
Syntax:
Package <Pack. Idn.>;
Advantage:
To manage related classes.
Software reuse.
Solves the problem of class name
conflict
To access classes in a package one
should use

1/Fully qualified class name


Syntax: <pack_name>.<class Idn.>
11/ Using import
Syntax: import <pack_name>.<* |
class Idn.>
Built in Java predefined
packages
Application programmer interface (API)
All classes provided to programmers along
with the Java compiler (e.g. Math or
MouseEvent)
Java expects to find these classes in
separate directories or folders
The classes stored in each directory form a
package
The package names are formed by
concatenating the directory names
starting from a particular root directory
Some Predefined Java Packages

Package Name Contents


java.applet Classes for implementing applets
java.awt Classes for graphics, windows, and GUI’s
java.awt.event Classes supporting AWT event handling
java.awt.image Classes for image handling
java.awt.peer Interface definitions for platform
independent graphical user interfaces (GUI’s)
java.io Classes for input and output
java.lang Basic language classes like Math
(always available in any Java program)
java.net Classes for networking
java.util Useful auxiliary classes like Date
Package Component
Names
Using a fully qualified component name
x = java.lang.Math.sqrt(3);
Using an import statement
// to allow unqualified references to
// all package classes
import package.name.*;
// to allow unqualified references to
// a particular package class
import package.name.class_name;
Import Examples
This code Can be abbreviated

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

You might also like