Sei sulla pagina 1di 30

Object Oriented Programming

with Java
Topic
Lecture 2
Object Oriented Paradigms in Java

Java Data Types and Operators


Encapsulation
Inheritance
Polymorphism
Java Security

19.03.18 Short Term Course on C++ 2


Data Types in Java
J a v a D a ta T y p e s

P r im it iv e D a t a T y p e s A b s tra c t D a ta T y p e s

N u m e r ic D a t a T y p e s N o n - n u m e r ic D a ta T y p e s C la s s e s A rra y s

In te rfa c e
In te g e r C h a ra c te r

F lo a t in g p o in t B o o le a n

19.03.18 Short Term Course on C++ 3


Java Primitive Data Types
Type Size Minimum value Maximum value

Integer Type

byte 1 byte -128 127

short 2 bytes -32,768 32,767

int 4 bytes -2,147,483,648 2,147,483,647

long 8 bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,807

Floating Point Type

float 4 bytes 3.4e-038 3.4e+037

double 8 bytes 1.7e-308 1.7e+307

Character Type

char 2 bytes Any single character (ASCII code)

Boolean Type

boolean 1 bit true (1) or false (0)

19.03.18 Short Term Course on C++ 4


Java Primitive Data Type Test
import java.io.DataInputStream;

class PrimitiveDataTypes
{
public static void main(String args[ ] ) {
DataInputStream in = DataInputStream(System.in);
boolean flag;
char c = ‘A’;
byte b = 63;
short shortInt;
int i;
long longInt;
float x;
double y;

System.out.println("Enter a small integer (say 123): ");


shortInt = System.in.read();

19.03.18 Short Term Course on C++ 5


Java Primitive Data Type Test
System.out.println("Enter an Integer (say 12345): ");
i = Integer.parseInt(in.readLine());

System.out.println("Enter a Long Integer (say 12345689L): ");


longInt = Long.parseLong(in.readLine());

System.out.println("Enter a float number (say 123.45): ");


x = Float.valueOf(in.readLine()).floatValue();

System.out.println("Enter a double number (say 9.87e-007): ");


y = Double.valueOf(in.readLine()).doubleValue();

System.out.println("shortInt = " + shortInt);


System.out.println("i = " + i);
System.out.println("longInt = " + longInt);
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}
19.03.18 Short Term Course on C++ 6
Arrays, Strings and Vectors in Java
• Array is a collection of homogeneous data
0 1 2 3 4 n -2 n -1

m a rk s

m a r k s .le n g th = n

• Following are the three tasks to manipulate an


Array in Java
– Declaration of an array
– Allocate memory for it
– Loading the values into array locations

19.03.18 Short Term Course on C++ 7


Arrays, Strings and Vectors in Java
• Declaration of an array • Initialization of an array
Examples Examples
int numbers[ ];
int numbers = {5, 4, 2, 1, 3}
float averageScores[ ];
float marks = {2.5, 3.4, 4.5}
int [ ] rollNo;
float [ ] marks;
What is the size of the array marks?
n = marks.length;
• Memory allocation for an array
Examples
numbers = new int [5]; How to define a two dimensional
averageScores = new float [20]; array?
rollNo = new int [49]; int a2Darray[ ] [ ];
marks = new float [54]; a2Darray = new int [4][7];

19.03.18 Short Term Course on C++ 8


Arrays, Strings and Vectors in Java
• Declaration of a String • Array of String
Examples Example
String listOfNames[ ]
String stringName; = new String [10];
stringName = new String(“Java”); listOfNames = {“aaa”, “bbb”, ... }

String myName = new String(“Atal”); What is the size of a String object


names?
size = names.length( );
String name = firstName + lastName;

How to compare two String objects, say


String name = “IIT” + “KGP” s1 and s2?
if (s1.compareTo(s2) = 0) then s1 and s2
are equal.

19.03.18 Short Term Course on C++ 9


Arrays, Strings and Vectors in Java
• Vector is nothing but an array, • Few usefull methods in the Vector
which can store any type of data class

• class Vector is a built-in type list.addElemnet(anItem)


defined in java.util package.
list.elementAt(i)
list.size()
• Defining a Vector type object list.removeElement(anItem)
Examples list.removeElementAt(i)
Vector list = new Vector(10); list.removeAllElements()
Here, list is a vector of size 10; list.copyInto(anArray)
This list can store any type of data list.insertElementAt(anItem, i)

19.03.18 Short Term Course on C++ 10


Encapsulation
• A class in Java is template to define an object
• General structure of a class
class ClassName [extends SuperClassName]
[implements InterfaceName]
{
[declaration of member elements ] {
[declaration of methods ]
}
}
Syntax for member elements:
DataType dataName;
Syntax for declaration of methods
[Modifier ] returnType methodName (parameter list){
Statements (s) ;
}

19.03.18 Short Term Course on C++ 11


Encapsulation: An Example
// Encapsulation :- Defining a class//

class Point
{
int x;
int y;
void getPoint ( int a, int b, ) {
x = a;
y = b;
}
}

19.03.18 Short Term Course on C++ 12


Encapsulation: An Example
// definition of another class. This is a main class

class Points
{
float distance;
public static void main (String args[ ] {
Point p1 =new Point( );
Point p2 = p1;
Point p3 = new Point ( );
Point p4 = new Point ( );
p1.getPoint (5, 10 );
p2.getPoint (15, 20);
p3.getPoint (20, 30);
p4.getPoint (30, 40);
System.out .println ( " X1 = " + p1.x + "Y1 = " + p1.y );
System.out .printlin ( "X2=" + p2.x + "Y2 = " +p2.y );
int dx = p3.x - p4. x; // X2 - X1
int dy = p3.y - p4. y; // y2 - y1
distance = Math.sqrt (dx * dx + dy * dy ); // (X2-X1)2 + (Y2-Y1)2
System.out.println ( " Distance = "+ distance );
}
}
19.03.18 Short Term Course on C++ 13
Constructor
Automatic Initialization of Objects
class Point ( ) {
int x, y;
Point ( int x, int y ) {
this.x = x ;
this.y = y;
}
printPoint() {
System.out.println("X = "+ this.x + " Y= " + this.y);
}

class PointCreate {
public static void main ( String args [ ] ) {
Point p = new Point (10, 20 );
p.printPoint();
}
}

19.03.18 Short Term Course on C++ 14


Overloading Constructor
Many ways to Initialize Objects
class Point ( ) {
int x, y;
Point ( int a, int a) { // Constructor for integer coordinates
x = a;
y = b;
}

Point ( float x, float y) { // Constructor for real coordinates


this.x = x;
this.y = y;
}

void printPoint() {
System.out.println("X = "+ this.x + " Y= " + this.y);
}

19.03.18 Short Term Course on C++ 15


Overloading Constructor
Many ways to Initialize Objects (Contd..)

class PointCreate {
public static void main ( String args [ ] ) {
Point p1 = new Point (10, 20 );
p1.printPoint();

Point p2 = new Point (5.5, 4.2 );


p2.printPoint();
}
}

19.03.18 Short Term Course on C++ 16


Inheritance in Java
• The mechanism of deriving
a new class from an old Super
class is called inheritance
• Java allows following three
types of inheritances
S uSp eu r b c la s s
– Single inheritance
– Multilevel inheritance
S u b c la s s 1 S u b c la s s 2 S u b c la s s 3
– Hierarchical inheritance
S u b c la s s

19.03.18 Short Term Course on C++ 17


Syntax for Inheritance in Java

Syntax of Single Inheritance Syntax of Hierarchical Inheritance


class subClassName extends superClassName { class subClassName1 extends superClassName {
declarations of members; declarations of members;
declarations of methods; declarations of methods;
} }
class subClassName2 extends superClassName {
Syntax of Multilevel Inheritance declarations of members;
class subClassName1 extends superClassName { declarations of methods;
declarations of members; }
declarations of methods;
} class subClassName3 extends superClassName {
class subClassName2 extends subClassName1 { declarations of members;
declarations of members; declarations of methods;
declarations of methods; }
}

19.03.18 Short Term Course on C++ 18


Example: Inheritance in Java
class Point ( ) {
int x, y;
Point ( int x, int y ) {
this.x = x ;
this.y = y;
}
}

class Point3D extends Point {


int z;
Point 3D (int x, int y, int z) { // A constructor of class Point3D
this.x =x;
this.y =y;
this.z =z;
}

void displayPoint ( ) {
System.out.println ( "X=" + x + " Y = " + y + " Z = " + z ) ;
}
}
19.03.18 Short Term Course on C++ 19
Polymorphism in Java
class Point {
int x,y;
Point ( int x, int y ) { // It is a constructor
this.x = x;
this.y = y;
}

/* P1*/ float distance ( int x, int y) { // One definition of distance


int dx = this x - x;
int dy = this y - y;
return float Math.sqrt ( dx* dx + dy * dy );
}

/* P2*/ float distance (Point p) { // Overloaded definition of distance


return distance ( p.x, p.y) ;
}

19.03.18 Short Term Course on C++ 20


Access Specification in Java
? Access Specification
• The mechanism by which one can control the use of objects,
its member elements and methods is known as the access
specification.

• This is done in Java by using the following access modifier


key words
– public
– private
– protected
– final
– abstract

19.03.18 Short Term Course on C++ 21


Access Specification in Java
• Public
– Member elements and methods can be marked as public and
then they can be accessed from any other method in Java
Programs.

– To indicate a method or element is public, precede it with the


public keyword .

– The public modifier can be applied to classes as well as methods


and variables. It then allows to make a class accessible to other
classes in other Packages.

– The public access specification is automatic, in the sense that, if


no access specifier is mentioned then by default it is having
public accessibility.

19.03.18 Short Term Course on C++ 22


Access Specification in Java
• Private
– Member elements and methods marked as private
can be used only from inside their class.

– A private element / method is not visible in any other


class, including subclasses .

– Also, a subclass cannot override a non-private


method and hence cannot make the new method
private.

19.03.18 Short Term Course on C++ 23


Access Specification in Java
• Protected
– Member elements and methods marked as protected
can be used only from inside their class or in
subclasses of that class.

– A subclass cannot override a protected method or


variable.

Note : It can be noted that the private and protected


modifier can not be applied to classes.

19.03.18 Short Term Course on C++ 24


Access Specification in Java
• Final
– In Java, one can declare that methods or member
elements cannot be allowed to override by
subclasses. For those method and member elements
final keyword can be specified.

– Like member elements and methods, classes also can


be declared final and once a class is specified as a
final class no inheritance will be possible from that
class.

19.03.18 Short Term Course on C++ 25


Access Specification in Java
• Abstract
– Just as one can specify that a method can never be sub classed
by marking it as final, one can indicate that a method must
always be sub classed by using the abstract keyword in the
method definition.

– When applied to a class, the abstract modifier indicates that the


class has not been fully implemented and that it should not be
instantiated.

– If applied to a member function declaration, the abstract


modifier means that the function will be implemented in a
subclass. Since the function has no implementation, the class
cannot be instantiated, and must be declared as abstract .

19.03.18 Short Term Course on C++ 26


Example: Access Specification
public class ClassA {
protected int x ;
private String s;
public void getData ( ) {
……… // Some code of getData( )
}

final void deleteData ( ) {


…..... // Some code of deleteData( )
}

private void printData ( ) {


…..... // Some code of printData( )
}
}

19.03.18 Short Term Course on C++ 27


Example: Access Specification

class ClassB extends ClassA {


……..
……..
…….
/ * Any method in this class
can access public and protected elements in ClassA
but not private elements * /

/* deleteData( ) can not be overridden here */

/* printData( ) cannot be accessed in any method in this class */

19.03.18 Short Term Course on C++ 28


Example: Access Specification

final class classC {


……
……
}

class ClassD extends ClassC { // Compilation error


….. // ClassC is a final class and hence
….. // cannot be inherited
}

19.03.18 Short Term Course on C++ 29


Example: Access Specification
abstract class ClassE {
……..
……..
abstract void anyMethod ( ) ;
}

public class ClassF {


public static void main ( String args [ ] ) {
……….
……….
ClassF = new Class F ( ) ; // Compile error :-
// ClassF is an abstract class and
// cannot be instantiated
// However, anyMethod( ) can be implemented here
// and can be used.
}
}
19.03.18 Short Term Course on C++ 30

Potrebbero piacerti anche