Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Java 1

Uploaded by

Goli
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Java 1

Uploaded by

Goli
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 47

Session 1

Java
Objectives:

 OOPs Concept.
 Object.
 Class.
 Abstruct Class.
 Interface.
 Package.

2
Object Oriented Programming
concept in Java

The history of computer programming is a
steady move away from machine-oriented
views of programming towards concepts
and descriptions that more closely reflect
the way in which we & ourselves
understand the world.

Programming has progressed through:
 machine code. [Mark I]
 assembly language [PDP-11]
 machine-independent programming languages [ Fortran]
 procedure & function Oriented. [Pascal]
 Object Oriented. [Java]
3
Object Orientation

In OOP, a program is seen as
comprising of a collection of objects,
which act on each other. Each object
has a distinct role or responsibility.

The responsibility of an object is the role
it serves within the system.

Object has following characteristics-
» State
» Behavior
» Attributes
» Identity
4
Object Orientation
Contd.

State is a set of properties which can take
different values at different times in the object’s
life.

Knowing Responsibility  State

Behavior is how an object reacts, in terms of its
state changes, in response to operations
performed upon it.

Doing Responsibility  Behavior

Attributes provide us a way to describe an object.

Identity is that property of an object which
distinguishes it from all other objects.
5
Properties of Object Orientated
Programming (OOP)
Common properties of OOP is given below-
• Abstraction
• Encapsulation.
• Inheritance.
• Polymorphism.
Abstraction –
One of the chief advantages of object-oriented
programming is the idea that programmers
can essentially focus on the “big picture” and
ignore specific details regarding the inner-
workings of an object. This concept is called
abstraction. 6
Properties of Object Orientated Programming(OOP)
Contd.

Encapsulation
• Abstraction in OOP is closely related to a
concept called encapsulation.
• Data and the ways to get at that data are
wrapped in a single package, a class. The
only way to access such data is through that
package. This idea translates to information
hiding.
• The wrapping up of data & methods into a
single unit (called class) is encapsulation.
7
Properties of Object Orientated Programming(OOP)
Contd.

Inheritance
• Another of the main belief of OOP is
inheritance.
• allows programmers to create new classes
from existing ones.
• A child class (discussed later) inherits its
properties and attributes from its parents,
which programmers can change.
• Inheritance is the eneralization/specialization
relationship between classes.
• The inheriting class inherits all the methods
and fields of the class it inherits from. 8
Properties of Object Orientated Programming(OOP)
Contd.

Polymorphism
• Polymorphism means “having many forms”. It
allows different objects to respond to the
same message in different ways, the
response specific to the type of the object.
• Polymorphism describes how programmers
write methods to do some general purpose
function. Different objects might perform
polymorphic methods differently.
• Polymorphism allows a single piece of code
to be reusable with many different types.
9
Java as Object Orientated
Programming

Java is an interpreted language. Java
compiler compiles the java source code to
obtain an object code termed “byte code” in
java terminology. The java interpreter will
interpret and run the byte code (object code)
at run time.

Java is platform independent language
because java byte code is transferable on
any computational unit to run, where java
interpreter is available.
10
Java as Object Orientated
Programming Contd.


The Java Development Kit (JDK) from
Sun Microsystems consists of an
extensive library of Java classes
called packages (discussed later). It
also contains the Java compiler and
the Java interpreter. It also provides a
very useful utility called applet viewer.


As language Java follows OOP
properties.
11
Java Objects & Class

Objects are the key to understanding object-
oriented technology. Real-world objects
share two characteristics:

They all have attribute and behavior.
Dogs have attribute (name, color, breed,
hungry) and behavior (barking, fetching,
wagging tail). Bicycles also have attribute
(current gear, current pedal cadence, current
speed) and behavior (changing gear,
changing pedal cadence, applying brakes).
Identifying the state and behavior for real-
world objects is a great way to begin thinking
in terms of object-oriented programming.
12
Java Objects & Class
Contd.

We encapsulate object attributes and
behaviors inside a class; whenever we need
to access those attributes and behaviors we
need to create an instance of the class.

Where Class is the prototype of an object.
When we need to keep a structure of an
object with its behavior and attributes, we
need a class.

In Java programming environment we also
need to find out our objects those have
attributes and behaviors to put them inside a
class.
13
Java Objects & Class
Contd.

Now how to find objects from Context ?

The nouns in the context may suggest the
objects in the problem domain, but all the
nouns are not going to represent objects.
Those noun phases have their doing
responsibility/ responsibilities (Behavior) we
will consider them to make objects.

Where the verbs in the context would
correspond to the object behaviors.

A class characterizes a set of objects that
share a common structure and a common
behavior. 14
Java Objects & Class
Contd.

Example:
• Mr. White is married. He teaches OO
Software Engineering classes on Fridays. He
is a part-time member of the faculty at the CS
Department of the All-Smart Institute. John is
enrolled in the OOSE class that Mr. White
teaches. Mrs. White uses a Nano for
transportation to and from the campus (she
teaches Philosophy at the same institute).
Class size is limited at the institute to 14
students. Janet, the sister of John is enrolled
for violin course in the same institute.
Identify all the objects & Similar
Objects / Class or Type that defines the objects … 15
Java Objects & Class
Contd.

OBJECTS are:
Mr. White Mrs. White John
Janet Student
Faculty Faculty Student

Nano Philosophy CS All-Smart


Car Department Department Institute

OOSE Violin
Course Course

16
Java Objects & Class
Contd.

Classes are:

Faculty Student Car Department

Institute Course

17

Example Java program to print “HELLO
WORLD”

class exampleHW
{
public static void main (String args[])
{
System.out.println (“HELLO WORLD” );
}
}

18
Java Introduction
 Java is now, general purpose programming language.
Java is a true OO language and therefore the
underlying structure of all Java programs is classes.

 Anything we wish to represent in Java must be


encapsulated in a class that defines the “state” and
“behavior” of the basic program components known
as objects.

19
Java Programming Elements
Java token set can be divided into five categories:

 Identifiers.
 Keywords.
 Literals.
 Operators.
 Separators.

20
Java Programming Elements
Contd.
Comments:

A note written in the source code by the programmer
to make the code easier to understand.
 Comments are not executed when your program
runs.
 Most Java editors show your comments with a
special colour.
Comment, general syntax:
/* <comment text; may span multiple lines> */
or,
// <comment text, on one line>
21
Java Programming Elements
Contd.
Java Datatypes

Datatypes determine how the compiler
identifies the contents of a memory location.

Java Datatypes can be divided into two
categories: Basic Datatypes and
Composite Datatypes.

Basic datatypes are known to compiler; like-
Integer, Character, Float, Boolean.

Composite datatypes are derived from the
basic datatypes. Composite datatypes in
java; like- arrays, string etc.
22
Java Programming Elements
Contd.
Datatype Size
byte 8 bits
short 16 bits
int 32 bits
long 64 bits
float 32 bits
double 64 bits

Character takes 16 bits, and Boolean takes 8


bits. 23
Java Programming Elements
Contd.
Arrays

An Array is a Container object that holds a fixed number of
values of a single type.

Array can contain both primitive and reference data types.

Each item in an array is called an element, and each element
is accessed by its numerical index.

Array Declaration
– int myIntegers[ ];
– int[ ] myIntegers; Indicates the same

Array memory allocation:
– int myIntegers[] = new int[10];

Array Initialization:
– int myIntegers[] = {1,2,3,4,5};
24
Java Programming Elements
Contd.
class ArrayDemo {
int[ ] arrayOfInts = new int[10];
void arrayEx(){
for (int j = 0; j < arrayOfInts.length; j ++){
arrayOfInts[j] = j;
System.out.print(arrayOfInts[j]);
}
} Output:
0123456789
25
Java Control structures

The statements inside your source files are generally
executed from top to bottom, in the order that they
appear. Control flow statements, however, break up
the flow of execution by employing decision making,
looping, and branching, enabling your program
to conditionally execute particular blocks of code.
This section describes the decision-making
statements (if-then, if-then-else, switch), the
looping statements (for, while, do-while), and the
branching statements (break, continue, return)
supported by the Java programming language.
26
Java Access Specifiers

27
Java Method
More generally, method declarations have six components, in
order:

Modifiers— such as public, private, and others you will learn
about later.

The return type—the data type of the value returned by the
method, or void if the method does not return a value.

The method name—the rules for field names apply to method
names as well, but the convention is a little different.

The parameter list in parenthesis —a comma-delimited list of
input parameters, preceded by their data types, enclosed by
parentheses, (). If there are no parameters, you must use empty
parentheses.

An exception list—to be discussed later.

The method body, enclosed between braces—the method's
code, including the declaration of local variables, goes here. 28
Java Method
Contd.
Example – Parameter list

public int method1 (int a, int b)

{ Identifier
Mothod_body;
} Return Type

Modifier

 Where Method Signature contains only the


identifier and the parameter list of a method.
29
Java Constructor

Constructor is a special method that gets invoked
“automatically” at the time of object creation.

Constructor has the same name as the class name.

Constructor cannot return values.

A class can have more than one constructor as long as they
have different signature (i.e., Constructor Overloading ).
class example_class
{
...
example_class (int a) // consrtuctor
{
}
...
} 30
Method Overloading

The Java programming supports language overloading methods,


and Java can distinguish between methods with different method
signatures. This means that methods within a class can have the
same name if they have different parameter lists.

• Method Overloading (Compile time Polymorphism)


• Two or more methods with different signatures.
• The functions which differ only in their return types cannot
be overloaded.
• The compiler will select the right function depending on the
type of parameters passed.

31
Method Overloading
Contd.
Example
Class ExampleMO
{
int method1 (int a)
{

}
int method1 (int a, int b) // overloaded method method1
{

}
} 32
Java Inheritance

Different kinds of objects often have a certain amount in
common with each other. Mountain bikes, road bikes, and
tandem bikes, for example, all share the characteristics of
bicycles (current speed, current pedal cadence, current gear).

Object-oriented programming allows classes
to inherit commonly used state and behavior from other
classes. In this example, Bicycle now becomes
the superclass of MountainBike, RoadBike, and TandemBike.
In the Java programming language, each class is allowed to
have one direct superclass, and each superclass has the
potential for an unlimited number of subclasses.

subclass extends superclass in java.

33
Java Inheritance
Contd.
Bicycle
is-a relationships

Mountain Racing Tandem


Bikes Bikes Bikes

class Mountain_Bike extends Bicycle


{

}
By the same way Racing_Bike & Tandem_Bike also
extends Bicycle.
34
Method Overriding
Contd .
• Method Overriding (Runtime Polymorphism)
• A method in the subclass to ‘override’ the method in super class
that has the same signature.
• Which method to be called, is determined at runtime, not at the
compile time.
• We used method overriding to achieve
polymorphism.
Example:
public class Animal {
public static void testClassMethod() {
System.out.println("The class method in Animal.");
}
public void testInstanceMethod() {
System.out.println("The instance method in Animal.");
35
}
The second class, a subclass of Animal, is called Cat:
public class Cat extends Animal {
public void testClassMethod() {
System.out.println("The class method in Cat.");
}
public void testInstanceMethod() {
System.out.println("The instance method in Cat.");
}
public static void main(String [] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
}
}
The output from this program is as follows:
The class method in Animal.
36
The instance method in Cat.
Abstract Classes
• An Abstract class is a conceptual class.

An Abstract class cannot be instantiated –
objects cannot be created.Abstract
classes provides a common root for a
group of classes, nicely tied together in a
package.

When a class contains one or more
abstract methods, it should be declared as
abstract class.

The abstract methods of an abstract class
must be defined in its subclass.

We cannot declare abstract constructors 37
Abstract Class -Example
• Shape is a abstract class.

Shape

Circle Rectangle

38 38
Abstract Class –Example
Contd.

public abstract class Shape {

public abstract double area();

public void move() { // non-abstract
method

// implementation

}

} //The abstract methods needs to be get
override in the corresponding sub classes.
39
Abstract Class – Example
Contd.
public Circle extends Shape {
protected double r;
protected static final double PI
=3.1415926535;
public Circle() { r = 1.0; )
public double area() { return PI * r * r; }

}
public Rectangle extends Shape {
protected double w, h;
public Rectangle() { w = 0.0; h=0.0; }
public double area() { return w * h; }
} 40
Interfaces
• Interface is a conceptual entity similar to a
Abstract class.
• Can contain only constants (final variables) and
abstract method (no implementation) - Different
from Abstract classes.
• Use when a number of classes share a common
interface.
• Each class should implement the interface.

41
Interface - Example
<<Interface>>
Speaker
speak()

Politician Priest Lecturer

speak() speak() speak()

42
Interfaces Definition
interface InterfaceName {
// Constant/Final Variable Declaration
// Abstract Methods
}
Example:-
interface Speaker {
public void speak( );
}
Implementing Interface:-
class ClassName implements InterfaceName [, InterfaceName2, …]
{
// Body of Class
}
43
Implementing Interfaces
Example
class Politician implements Speaker {
public void speak(){
System.out.println(“Talk politics”);
}
}
class Priest implements Speaker {
public void speak(){
System.out.println(“Religious Talks”);
}
}
class Lecturer implements Speaker {
public void speak(){
System.out.println(“Talks Object Oriented Design and
Programming!”);
}
}

44
Java Packages


A package is a grouping of related types providing
access protection and name space management.

The types that are part of the Java platform are
members of various packages that bundle classes by
function: fundamental classes are in java.lang,
classes for reading and writing (input and output) are
in java.io, and so on. You can put your types in
packages too.

45
Java Packages Contd.
Example:
package points;
class Point {
int x, y; // coordinates
PointColor color; // color of this point
Point next; // next point with this color
static int nPoints;
}
class PointColor {
Point first; // first point with this color
PointColor(int color) {
this.color = color;
}
private int color; // color components
46
}
Java Packages Contd.

defines two classes that use each other in the declarations


of their class members. Because the class types Point
and PointColor have all the type declarations in package
points, including all those in the current compilation unit,
as their scope, this example compiles correctly-that is,
forward reference is not a problem.

Whenever we need to include the package, we need to


write;
‘import java.points’

47

You might also like