Lecture 8

advertisement
-
Aggregation
UML diagram
Self-Referential Classes
Generisity
1
Class Circle
public 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
Point
public 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 Point
3
Aggregation (‫)הכלה‬
public class Circle
{
private Point center; // another object !
private double radius; // circles radius
public Circle( Point center, double radius )
{
Aggregation is a relationship
this.center = center;
between two classes.
this.radius = radius;
The aggregate class contains a
} // class Point constructor
reference to another class.
public Point getCenter()
{
return this.center;
These methods use reference center to
}
another object Point .
public double getRadius()
{
return this.radius;
}
// rest methods
Aggregation – example 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
c1
Circle (c1)
Point (p1)
center
radius
p1
5.0
p1
x
y
7.4
9.5
5
Access to point coordinates
public 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();
We use getter methods
from Point object
double c1CenterY = c1Center.getY();
double c1Radius = c1.getRadius();
System.out.println(“x= “+ c1CenterX+” y= “+c1CenterY + “ r= “+ c1Radius);
// another choice
c1CenterX = c1.getCenter(). getX();
We use getter methods
c1CenterY = c1.getCenter(). getY();
from Circle object
p1.printPoint();
} // main
This program generates the following output:
x = 7.4 y = 9.5 r = 5.0
x = 7.4 y = 9.5
6
Rectangle
definition
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 ).
y - axis
y - axis
topRight
width
height
x - axis
bottomLeft
x - axis
bottomLeft
7
Class
Rectangle
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
8
Class
Rectangle, cont.
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
9
Class
Rectangle, cont.
public static void main(String[] args)
Rectangle:
{
bottom-left point : x = 2.0 y =1.0
top-right point : x = 7.0 y = 5.0
Point p1 = new Point(2,1);
Rectangle:
Point p2 = new Point(7,5);
bottom-left point : x = 2.0 y =1.0
Rectangle rect1 = new Rectangle(p1,p2); top-right point : x = 8.0 y = 4.0
area = 20.0
System.out.println(rect1);
perimeter = 18.0
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
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
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.
Rectangle
Point
public double x
Point bottonLeft
public double y
Point topRight
Point(double x, double y)
Rectangle( Point bottonLeft, Point topRight)
double getX()
Rectangle( Point bottonLeft, double width, double height)
double getY()
double getArea()
void setX(double x)
double getPerimeter()
void setY(double y)
void move(double deltaX, double deltaY)
String toString()
String toString()
12
UML Diagram – Example2
● UML diagrams allow us to denote the relationships
between classes.
● In a UML diagram we can show the class member variables
and class methods.
Student
String name
int ID
Lecturer
Lecturer lecturer
String name
Student(String name, int ID, Lecturer lecturer)
int depCode
String getName()
Lecturer(String name,int depCode)
void setID( int ID)
String getName()
Lecturer getLecturer()
void setDepCode( int depCode)
13
Aggregation – example 2
Lecturer lect = new Lecturer(“Alex”, 777);
Student s1 = new Student(“David”, 1234567, lect);
Student s2 = new Student(“Ronit”, 7654321, lect);
Student
Student
name
ID
lecturer
name
ID
lecturer
David
1234567
lect
Ronit
7654321
lect
s1
s2
Lecturer
lect
name
depCode
Alex
777
14
Array of objects
Student [ ] arr = new Student [ 5 ];
arr[ ]
arr
0
1
2
3
4
null
null
null
null
null
Lecturer lect = new Lecturer(“Alex”, 777);
arr[0] = new Student(“David”,1234567,lect);
arr[1] = new Student(“Ronit”,7654321,lect);
arr[ ]
0
1
2
3
4
arr[0]
arr[1]
null
null
null
Student
Student
name
ID
lecturer
name
ID
lecturer
David
1234567
lect
Ronit
7654321
lect
15
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 is sorted.
Shift nothing. Insert 9.
3
9
6
1
2
3 and 9 are sorted.
Shift 9 to the right.
Insert 6.
3
6
9
1
2
1
3
6
9
2
1,3 ,6 and 9 are sorted.
Shift 9,6 and 3 to the
right. Insert 2.
1
2
3
6
9
All values are sorted16
3 ,6 and 9 are sorted.
Shift 9,6 and 3 to the
right. Insert 1.
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
Insertion sort of integer array
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 How compare two
object values ?
arr[j] = a;
} // block for
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];
We use only getter methods
to access student ID value
j--;
} // block while
arr[j] = val;
} // block for
} // insertSort
18
Invoke insertSort method
public 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
UML diagram to define class
StudList
StudList
int
MAX_STUD
Student [ ]
int
list
Class variables
lastPos
StudList()
void
Constructor
addStud(String name)
Student
delStud(String name)
Student
getStud(String name)
void
Class name
Class methods
printStudList()
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 method adds new
this.list[ this.lastPos ] = st;
student to StudList class.
this.lastPos++;
} // addStud
21
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;
}
This method removes the student from
return st;
StudList class and returns a reference to
} // delStud
removed value. If the student does not exist
in the class , the method returns null.
22
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)
This method returns a reference to a student if
st = this.list[i];
his name exists in the StudList class.
return st;
If the student does not exist in the class , the
method returns null.
} // 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
Class StudList – delSdud test
public 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 test
public 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 Classes
A 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;
}
Field nextNode references a Node
object, an object of the same class .
First constructor has only one
argument for the item; the next
field is set to null.
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;
}
This method allows modification of
the nextNode field.
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.
27
Building a linked list from Node objects
Node n = new Node(9);
Node
n
data
nextNode
9
null
Node n1 = new Node(4,n);
n1
Node
data
n
Node
nextNode
4
data
nextNode
9
null
Node n2 = new Node(5,n1);
n2
Node
data
5
nextNode
n1
Node
data
4
nextNode
n
Node
data
nextNode
9
null
28
Building a linked list from Node objects
public static void main(String[ ] args)
{
System.out.print("enter the number of nodes ");
Input data values:
int num = reader.nextInt(); // num = 5
System.out.print("enter the data value ");
1
int data = reader.nextInt();
2
Node n = new Node(data);
3
for( int i = 1; i < num; i++)
4
{
5
System.out.print("enter the data value ");
data = reader.nextInt();
Output ?
n = new Node(data,n);
} // for
while( n != null )
{
String str = n.toString();
System.out.println(n);
System.out.println(str);
n = n.getNext();
} //while
} // main
29
Inserting a node in a linked list
Node
temp
data
nextNode
Inserted Node
7
Node
temp
data
Node temp = new Node(7, n.getNext());
nextNode
7
Node
n
data
Node
nextNode
data
5
4
nextNode
Node
data
nextNode
9
null
n.setNext(temp);
30
Deleting a node from a linked list
Node
n
data
nextNode
data
5
data
temp
nextNode
5
nextNode
data
nextNode
9
null
Node
nextNode
4
Node
data
nextNode
Node
data
5
n
Node
4
Node
n
Node
temp
data
nextNode
9
null
Node
temp
Node
data
nextNode
4
null
1.Node temp=n.getNext();
2.n.setNext( temp.getNext() );
3.temp.setNext(null);
data
nextNode
9
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 class Node
{
private String data;
private Node nextNode;
public Node( String data )
{
this.data = data;
}
public Node(int data,Node nextNode)
{
this.data = data;
this.nextNode = nextNode;
}
public Node(String data,Node nextNode)
{
this.data = data;
this.nextNode = nextNode;
}
public void setData( int data )
{
this.data = data;
}
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
T is a place holder
(‫(מחזיק מקום‬
Node<T>
private T data
private Node<T> nextNode
Class
variables
Node(T x)
Node( T data, Node<T> nextNode)
constructors
T getData()
Node<T> getNext()
Void setData( T data)
Class methods
Void setNext(Node<T> nextNode)
String toString()
35
Generic class Node
public 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
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);
Node<Point>
np
data
nextNode
p
null
ns
Node<String>
data
nextNode
s
null
Point
X
Y
4.0
5.0
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”));
np
Node<Point>
data
nextNode
Node<Point>
data
Node<String>
nextNode
data
null
s
p
Point
ns
nextNode
Node<String>
data
nextNode
null
Point
X
Y
X
Y
4.0
5.0
8.0
9.0
String
String
Hello
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
Base case
Input:
Ofir
Galit
David
Ronit
Output:
Ofir -> Galit -> David -> Ronit
41
Linked list – recursion 2
Recursive method getClassLength returns the length of
linked list.
public static int getClassLength(Node<String> s)
{
if(s.getNext( ) == null)
Base case
return 1;
return 1 + getClassLength(s.getNext( ));
} // getClassLenght
42
Linked list – recursion 3
Recursive method getXposition returns the reference to
integer X value position in the linked list ( null if not found).
public static Node<Integer> getXposition(Node<Integer> pos, int x)
{
if( pos.getData( ) == x )
Base case
return pos;
if( pos.getNext( ) == null )
return null;
return getXposition( pos.getNext( ), x);
} // getPosition
Download