3. Outlines
◉ User defined type
◉ Array of User defined type (new class)
◉ Passing Objects to Methods
◉ Immutable Objects and Classes
◉ Full Example
Note: I have prepared this material Based on (Liang: “Introduction to Programming using Java”, 10’th edition, 2015)
5. o As the defined class is a new data type, we can defined any
variables or arrays of it.
User defined type
6. Array of User defined type
int sal;
int id;
String name;
…
Employee class
e1
e2
e3
e4
e5
e6
e7
e8
Employee [ ] x ;
7. Array of User defined type
o An array of objects is actually an array of reference variables.
Circle[] circleArray = new Circle[10];
8. Array of User defined type
Class [ ] x ;
Add objects
Delete objects
Looking for objects
Printing all data
….
Class
To management many objects
which are stored in array
9. o Passing by value for primitive type value (the value is passed to
the parameter)
o Passing by value for reference type value (the value is the
reference to the object)
Passing Objects to Methods
11. o For a class to be immutable, it must mark all data fields private
and provide no mutator methods and no accessor methods that
would return a reference to a mutable data field object.
o If the contents of an object cannot be changed once the object
is created, the object is called an immutable object and its class
is called an immutable class.
Immutable Objects and Classes
12. Immutable ?
public class Student {
private int id;
private BirthDate birthDate;
public Student(int ssn,
int year, int month, int day) {
id = ssn;
birthDate = new BirthDate(year, month, day);
}
public int getId() {
return id;
}
public BirthDate getBirthDate() {
return birthDate;
}
}
public class BirthDate {
private int year;
private int month;
private int day;
public BirthDate(int newYear,
int newMonth, int newDay) {
year = newYear;
month = newMonth;
day = newDay;
}
public void setYear(int newYear) {
year = newYear;
}
}
13. Example: ContactBook
int serial;
String name;
String mobile;
String address;
…
Contact class
int count;
void search(){}
void print(){}
void insert(){}
…
ManagArray class
e1
e2
e3
e4
e5
e6
e7
e8
Contact [ ] conArray ;
14. Contact book
class Contact {
private String name;
//….
public Contact (String name, String mobile) { … }
}
class ManagArray {
private Contact [ ] contBook;
private int count;
// …
public ManagArray(int size){ … }
public void insert(Contact c) { …. }
public void printData() { … }
public void searchByName(String name) { … }
}
15. static int x;
class Test
obj1
X = 0X = 1
obj2
X = 2
obj3
X = 3
Now:
Print Obj1.X
3
Print Obj1.X
3
Print Obj1.X
3
16. Practices
Group 1
Give 3 examples to
array of objects.
Group 2
Diffrenciate between
Passing by value and
by reference.
Group 3
Develop Immutable
class.