- Aggregation - UML diagram - Self-Referential Classes...

Post on 22-Jun-2020

6 views 0 download

Transcript of - Aggregation - UML diagram - Self-Referential Classes...

1

- Aggregation

- UML diagram

- Self-Referential Classes

- Generisity

Class Circlepublic class Circle

{

private double xCenter; // x center coordinate

private double yCenter; // y center coordinate

private double radius; // circles radius

public Circle(double xCenter, double yCenter, double radius )

{

this.xCenter = xCenter;

this.yCenter = yCenter;

this.radius = radius;

} // class Circle constructor

// rest methods

.

.

.} // class Circle 2

Class Pointpublic class Point

{

private double x; // x coordinate

private double y; // y coordinate

public Point(double x, double y)

{

this.x = x;

this.y =y;

} // class Point constructor

public double getX( ) {

return this.x;

}public void printPoint() {

System.out.println( "x = “ + this.x + "y = “ + this.y);

} // printPoint()

// rest methods

} // class Point3

Aggregation (הכלה)

public class Circle

{

private Point center; // another object !

private double radius; // circles radius

public Circle( Point center, double radius )

{

this.center = center;

this.radius = radius;

} // class Point constructor

public Point getCenter()

{

return this.center;

}

public double getRadius()

{

return this.radius;

}

// rest methods

Aggregation is a relationship

between two classes.

The aggregate class contains a

reference to another class.

These methods use reference center to

another object Point .

Aggregation – example 1

Circle (c1)

center radius

p1 5.0

c1

Point (p1)

x y

7.4 9.5

p 1

Point p1 = new Point(7.4,9.5); // create new point

Circle c1 = new Circle(p1,5.0); // create new circle : reference to object p1

5

Access to point coordinatespublic static void main(String[ ] args)

{

Point p1 = new Point(7.4,9.5); // create new point

Circle c1 = new Circle(p1,5.0); // create new circle

Point c1Center = c1.getCenter();

double c1CenterX = c1Center.getX();

double c1CenterY = c1Center.getY();

double c1Radius = c1.getRadius();

System.out.println(“x= “+ c1CenterX+” y= “+c1CenterY + “ r= “+ c1Radius);

// another choice

c1CenterX = c1.getCenter(). getX();

c1CenterY = c1.getCenter(). getY();

p1.printPoint();} // main

We use getter methods

from Point object

This program generates the following output:

x = 7.4 y = 9.5 r = 5.0

x = 7.4 y = 9.5

We use getter methods

from Circle object

6

Rectangle definition

7

Rectangle is any quadrilateral with four right angles.

The word rectangle comes from the Latin rectangulus, which is a combination

of rectus ( right ) and angulus ( angle ).

bottomLeft

topRight

x - axis

y - axis

bottomLeft

x - axis

y - axis

width

height

Class Rectangle

8

public class Rectangle {

private Point bottomLeft;

private Point topRight;

public Rectangle (Point bottomLeft, Point topRight)

{

this.bottomLeft = bottomLeft;

this.topRight = topRight;

} // constructor1

public Rectangle (Point bottomLeft, double width, double height)

{

this.bottomLeft = new Point(bottomLeft);

this.topRight = new Point(bottomLeft.getX() + width, bottomLeft.getY() + height);

} // constructor2

public double getArea()

}

double width = this.topRight.getX() - this.bottomLeft.getX();

double height = this.topRight.getY() - this.bottomLeft.getY();

return width * height;

{ // getArea

Class Rectangle, cont.

9

public double getPerimeter()

{

double width = this.topRight.getX() - this.bottomLeft.getX();

double height = this.topRight.getY() - this.bottomLeft.getY();

return (2 * width) + (2 * height);

{ // getPerimeter

public void move (double deltaX, double deltaY)

{

this.topRight.setX(this.topRight.getX() + deltaX);

this.topRight.setY(this.topRight.getY() + deltaY);

this.bottomLeft.setX(this.bottomLeft.getX() + deltaX);

this.bottomLeft.setY(this.bottomLeft.getY() + deltaY);

{ // move

public String toString() {

return "Rectangle:" + "\n" +

"bottom-left point : " + this.bottomLeft.toString() + "\n" +

"top-right point : " + this.topRight.toString();

{ // toString

} // class Rectangle

Class Rectangle, cont.public static void main(String[] args)

{

Point p1 = new Point(2,1);

Point p2 = new Point(7,5);

Rectangle rect1 = new Rectangle(p1,p2);

System.out.println(rect1);

double width = 6.0;

double height = 3.0;

Rectangle rect2 = new Rectangle(p1,width,height);

System.out.println(rect2);

System.out.println("area = " + rect1.getArea());

System.out.println("perimeter = "+ rect2.getPerimeter());

} // main

10

Rectangle:

bottom-left point : x = 2.0 y =1.0

top-right point : x = 7.0 y = 5.0

Rectangle:

bottom-left point : x = 2.0 y =1.0

top-right point : x = 8.0 y = 4.0

area = 20.0

perimeter = 18.0

Encapsulation (הכמסה)

• One of the important object-oriented techniques is hiding the

data הסתרת מידע ) ( within the class, and making it available

only through the methods.

• This technique is often known as encapsulation, because it

seals the class's data (and internal methods) safely inside the

"capsule" of the class, where it can be accessed only by

trusted users- i.e., by the methods of the class.

• The most important reason is to hide the internal

implementation details of your class. If a variable is visible

only in your class, you have to document it.

11

Rectangle

Point bottonLeft

Point topRight

Rectangle( Point bottonLeft, Point topRight)

Rectangle( Point bottonLeft, double width, double height)

double getArea()

double getPerimeter()

void move(double deltaX, double deltaY)

String toString()

UML Diagram – Example1

• UML stands for Unified Modeling Language. It's a way to

represent object-oriented applications using graphical

diagrams.

• UML shows the classes of the system, their relationships, and

the operations and attributes of the classes.

12

Point

public double x

public double y

Point(double x, double y)

double getX()

double getY()

void setX(double x)

void setY(double y)

String toString()

UML Diagram – Example2

13

Lecturer

String name

int depCode

Lecturer(String name,int depCode)

String getName()

void setDepCode( int depCode)

Student

String name

int ID

Lecturer lecturer

Student(String name, int ID, Lecturer lecturer)

String getName()

void setID( int ID)

Lecturer getLecturer()

● UML diagrams allow us to denote the relationships

between classes.

● In a UML diagram we can show the class member variables

and class methods.

Aggregation – example 2

Lecturer

name depCode

Alex 777lect

Student

name ID lecturer

David 1234567 lect

Student

name ID lecturer

Ronit 7654321 lect

s1 s2

14

Lecturer lect = new Lecturer(“Alex”, 777);

Student s1 = new Student(“David”, 1234567, lect);

Student s2 = new Student(“Ronit”, 7654321, lect);

Array of objects

Student [ ] arr = new Student [ 5 ];

arr[ ]

0 1 2 3 4

null null null null null

arr

arr[ ]

0 1 2 3 4

arr[0] arr[1] null null null

Lecturer lect = new Lecturer(“Alex”, 777);

arr[0] = new Student(“David”,1234567,lect);

arr[1] = new Student(“Ronit”,7654321,lect);

Student

name ID lecturer

David 1234567 lect

Student

name ID lecturer

Ronit 7654321 lect15

Insertion sort - reminder

The insertion sort algorithm works by inserting each value into a previously

sorted subset of the list.

3 9 6 1 2

3 9 6 1 2

3 6 9 1 2

1 3 6 9 2

1 2 3 6 9

3 is sorted.

Shift nothing. Insert 9.

3 and 9 are sorted.

Shift 9 to the right.

Insert 6.

3 ,6 and 9 are sorted.

Shift 9,6 and 3 to the

right. Insert 1.

1,3 ,6 and 9 are sorted.

Shift 9,6 and 3 to the

right. Insert 2.

All values are sorted16

Sorting array of objects

public class Student

{

private String name;

private int id;

public Student( int id, String name)

{

this.name = name;

this.id = id;

} // class Student constructor

public int getId( )

{

return this.id;

}

// rest methods

.

.

.

} // class Student

int [ ] arr = { 3, 9, 6, 1, 2 };

for (int i = 1; i < arr.length; i++)

{

int j = i;

int a = arr[i];

while ( j > 0 && arr[j-1] > a)

{

arr[j] = arr[j-1];

j--;

} // block while

arr[j] = a;

} // block for

Insertion sort of integer array

How compare two

object values ?

17

Sorting array of objects,cont.

public static void insertSort( Student [ ] arr)

{

for (int i = 1; i < arr.length; i++)

{

Student val = arr[i]; // reference to arr[i]

int j = i;

while( j>0 && ( arr[j-1].getId() > val.getId()))

{

arr[j] = arr [j-1];

j--;

} // block while

arr[j] = val;

} // block for

} // insertSort

We use only getter methods

to access student ID value

18

Invoke insertSort methodpublic static void main(String[ ] args)

{

System.out.print("enter number of student ");

int num = reader.nextInt();

Student [ ] arr = new Student[num];

for( int i = 0; i < num; i++)

{

System.out.print("enter student ID " );

int id = reader.nextInt();

System.out.print("enter student name " );

String name = reader.next();

arr[i] = new Student( id, name );

} // for

insertSort(arr); // invoke insertSort method

for( int j = 0; j < num; j++)

System.out.println("studID = “ + arr[j].getId());

} // main

We use getId() getter method

to access j student ID value

19

Class StudList - UML

StudList

int MAX_STUD

Student [ ] list

int lastPos

StudList()

void addStud(String name)

Student delStud(String name)

Student getStud(String name)

void printStudList()

UML diagram to define class

StudList

Class name

Class variables

Class methods

Constructor

20

Class StudList - implementation

public class StudList

{

public static final int MAX_STUD = 100;

private Student [ ] list; // array of Student type

private int lastPos; // last free position

public StudList()

{

this.list = new Student[MAX_STUD];

this.lastPos = 0;

} // StudList class constructor

public void addStud( Student st )

{

this.list[ this.lastPos ] = st;

this.lastPos++;

} // addStud

21

This method adds new

student to StudList class.

Class StudList – implementation,cont.

public Student delStud(String name)

{

Student st = null;

int i = 0;

while( i < this.lastPos && this.list[i].getName().compareTo(name) != 0 )

i++;

if(i < this.lastPos)

{

st = this.list[i];

for( int k = i+1; k < this.lastPos; k++ )

this.list[k-1] = this.list[k];

this.lastPos--;

this.list[this.lastPos] = null;

}

return st;

} // delStud

22

This method removes the student from

StudList class and returns a reference to

removed value. If the student does not exist

in the class , the method returns null.

Class StudList – implementation,cont.

public Student getStud( String name )

{

Student st = null;

int i = 0;

while( i< this.lastPos && this.list[i].getName().compareTo(name) != 0 )

i++;

if(i < this.lastPos)

st = this.list[i];

return st;

} // getStud

public void printStudList()

{

for( int i = 0; i< this.lastPos; i++ )

System.out.println( "ID = “ + this.list[i].getId() + " name = “ + this.list[i].getName());

} // printStudList

} // class StudList

23

This method returns a reference to a student if

his name exists in the StudList class.

If the student does not exist in the class , the

method returns null.

Class StudList – delSdud testpublic static void main(String[ ] args) {

System.out.print( “Enter number of student " );

int num = reader.nextInt( );

StudList stL = new StudList( );

for( int i = 0; i < num; i++) {

int id = reader.nextInt();

String name = reader.next();

Student st = new Student(id,name);

stL. addStud(st); } // for

stL.printStudList( ) ;

System.out.print(“Enter student name to delete " );

String nmd = reader.next( ) ;

Student d = stL.delStud(nmd);

if(d == null)

System.out.println( “Student not found !" );

else

System.out.println( “Student “ + nmd + “delete" );

stL.printStudList();

} // main 24

Class StudList – getStud testpublic static void main(String[ ] args) {

System.out.print( “Enter number of student " );

int num = reader.nextInt( );

StudList stL= new StudList( );

for( int i = 0; i < num; i++) {

int id = reader.nextInt();

String name = reader.next();

Student st= new Student( id,name);

stL. addStud(st); } // for

stL.printStudList( ) ;

System.out.print(“Enter student name " );

String nmf = reader.next( ) ;

Student f = getStud(nmf);

if(f == null)

System.out.println( “Student not found ! " );

else

System.out.println( “Student “ + nmf + “found" );

} // main

25

Self - Referential ClassesA self-referential class contains a reference member that

refers to a class object of the same class type.

public class Node

{

private int data;

private Node nextNode;

public Node( int data )

{

this.data = data;

} // class Node constructor1

public Node( int data,Node nextNode)

{

this.data = data;

this.nextNode = nextNode;

} // class Node constructor2

public void setData( int data )

{

this.data = data;

}

First constructor has only one

argument for the item; the next

field is set to null.

Field nextNode references a Node

object, an object of the same class .

Node object can be created to

point to the next Node object.

26

Class Node ,cont.public int getData()

{

return this.data;

}

public void setNext( Node nextNode )

{

this.nextNode = nextNode;

}

public Node getNext()

{

return this.nextNode;

}

public String toString()

{

return " " + this.data.toString();

}

} // end class Node

Java can link self-referential objects

together to form such useful data

structures as lists, queues, stacks and

trees.

This method allows modification of

the nextNode field.

27

Building a linked list from Node objects

Node n = new Node(9);

Node n1 = new Node(4,n);

Node n2 = new Node(5,n1);

Node

data nextNode

9 null

n

Node

data nextNode

9 null

Node

data nextNode

4

n1 n

Node

data nextNode

5

Node

data nextNode

4

Node

data nextNode

9 null

n2 n1 n

28

Building a linked list from Node objects

public static void main(String[ ] args)

{

System.out.print("enter the number of nodes ");

int num = reader.nextInt(); // num = 5

System.out.print("enter the data value ");

int data = reader.nextInt();

Node n = new Node(data);

for( int i = 1; i < num; i++)

{

System.out.print("enter the data value ");

data = reader.nextInt();

n = new Node(data,n);

} // for

while( n != null )

{

String str = n.toString();

System.out.println(str);

n = n.getNext();

} //while

} // main

Input data values:

12345

Output ?

System.out.println(n);

29

Inserting a node in a linked list

Node

data nextNode

7

temp

Node

data nextNode

7

Node

data nextNode

5

n Node

data nextNode

4

Node

data nextNode

9 null

Node temp = new Node(7, n.getNext());

n.setNext(temp);

temp

30

Inserted Node

Deleting a node from a linked list

Node

data nextNode

5

Node

data nextNode

4

Node

data nextNode

9 null

n temp

Node

data nextNode

5

Node

data nextNode

4

Node

data nextNode

9 null

n temp

Node

data nextNode

5

Node

data nextNode

4 null

Node

data nextNode

9 null

n temp

1.Node temp=n.getNext();2.n.setNext( temp.getNext() );3.temp.setNext(null);

31

Calculate sum in a linked list

public static int calcSum( Node n)

{

int sum = 0;

Node currPos = n; // reference to first node

while( currPos != null )

{

sum = sum + currPos.getData();

currPos = currPos.getNext();

} // while

return sum;

} // calcSum

32

Max value position in a linked list

public static Node findMaxPos( Node n)

{

Node maxPos = n; // searching from this place

n = n.getNext();

while(n != null )

{

if( n.getData() > maxPos.getData() )

maxPos = n;

n = n.getNext();

} // while

return maxPos;

} // findMaxPos

33

What are the differences?public class Node

{

private int data;

private Node nextNode;

public Node( int data )

{

this.data = data;

}

public Node(int data,Node nextNode)

{

this.data = data;

this.nextNode = nextNode;

}

public void setData( int data )

{

this.data = data;

}

public class Node

{

private String data;

private Node nextNode;

public Node( String data )

{

this.data = data;

}

public Node(String data,Node nextNode)

{

this.data = data;

this.nextNode = nextNode;

}

public void setData( String data )

{

this.data = data;

}

34

Genericity (מנגנון הגנריות)• Genericity is a mechanism to specify the types of objects that a

class can work with via parameters passed at declaration-time and

evaluated at compile-time.

• Generic programming is the creation of programming constructs that

can be used with many different types.

UML diagram to define generic class Node

Node<T>

private T data

private Node<T> nextNode

Node(T x)

Node( T data, Node<T> nextNode)

T getData()

Node<T> getNext()

Void setData( T data)

Void setNext(Node<T> nextNode)

String toString()

constructors

Class

variables

Class methods

T is a place holder( מחזיק מקום)

35

Generic class Nodepublic class Node <T>

{

private T data;

private Node<T> nextNode;

public Node( T data )

{

this.data = data;

} // class Node<T> constructor1

public Node(T data, Node<T> nextNode)

{

this.data = data;

this.nextNode = nextNode;

} // class Node<T> constructor2

public void setData( T data )

{

this.data =data;

}

36

Generic class Node, cont.public T getData()

{

return this.data;

}

public void setNext( Node<T> nextNode )

{

this.nextNode = nextNode;

}

public Node<T> getNext()

{

return this.nextNode;

}

public String toString()

{

return " " + this.data;

}

} // end class generic Node 37

Generic class Node - implementation

Node<Point>

data nextNode

p null

Point p = new Point(4.0,5.0));

Node<Point> np = new Node<Point>(p);

String s = “Hello”;

Node<String> ns = new Node<String>(s);

Point

X Y

4.0 5.0

np Node<String>

data nextNode

s null

ns

String

Hello

38

Generic class Node - implementation,cont.

np.setNext(new Node<Point>(new Point(8.0,9.0)));

ns.setNext(new Node<String>(“Java”));

Node<Point>

data nextNode

p

Node<Point>

data nextNode

null

np

Point

X Y

4.0 5.0

Point

X Y

8.0 9.0

Node<String>

data nextNode

s

Node<String>

data nextNode

null

ns

String

Hello

String

Java

39

Generic class Node - test

public static void main(String[ ] args)

{

System.out.print( "enter number of student " );

int num = reader.nextInt( ); // num=4

System.out.print("enter the name ");

String name = reader.next();

Node<String> ns = new Node<String>(name);

Node<String> startPos = ns; // help variable

for(int i =1; i < num; i++)

{

System.out.print("enter the name ");

name = reader.next();

ns.setNext(new Node<String>(name));

ns = ns.getNext();

} // for

printClass(startPos); // recursive method (next slide)

} // main

40

Linked list – recursion 1

public static void printClass(Node<String> s)

{

System.out.print(s.getData());

if(s.getNext() != null)

{

System .out.print(" -> ");

printClass(s.getNext());

}

} // printClass

Input:

Ofir

Galit

David

Ronit

Output:

Ofir -> Galit -> David -> Ronit

Base case

41

Linked list – recursion 2

42

public static int getClassLength(Node<String> s)

{

if(s.getNext( ) == null)

return 1;

return 1 + getClassLength(s.getNext( ));

} // getClassLenght

Base case

Recursive method getClassLength returns the length of

linked list.

Linked list – recursion 3

public static Node<Integer> getXposition(Node<Integer> pos, int x)

{

if( pos.getData( ) == x )

return pos;

if( pos.getNext( ) == null )

return null;

return getXposition( pos.getNext( ), x);

} // getPosition

Base case

Recursive method getXposition returns the reference to

integer X value position in the linked list ( null if not found).