[go: up one dir, main page]

0% found this document useful (0 votes)
8 views27 pages

Lecture 2

This document is a lecture on Object-Oriented Programming with Java, focusing on concepts such as accessor and mutator methods, constructor overloading, encapsulation, and scoping rules. It includes examples of class definitions, method signatures, and UML class diagrams. Additionally, it outlines assignments related to creating classes for time, employee, and date with specified attributes and methods.

Uploaded by

ahmeddhamed179
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views27 pages

Lecture 2

This document is a lecture on Object-Oriented Programming with Java, focusing on concepts such as accessor and mutator methods, constructor overloading, encapsulation, and scoping rules. It includes examples of class definitions, method signatures, and UML class diagrams. Additionally, it outlines assignments related to creating classes for time, employee, and date with specified attributes and methods.

Uploaded by

ahmeddhamed179
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Object Oriented

Programming
with Java II

Dr. Mohamed K. Hussein


Lecture 2

Associate Prof., Computer Science department,

Faculty of Computers & Information Science,

Suez Canal University

Email: m_khamis@ci.suez.edu.eg
Lecture outcomes
• What are accessor and mutator methods.

• How they can be used in conjunction with encapsulation.

• What is constructor overloading.

• How to represent a class using class diagrams.

• Attributes, methods and access permissions.

• Scoping rules

• Addresses & References

Dr. Mohamed K. Hussein 2


Viewing & Modifying Attributes
Accessor & Mutators
public int getAge() {
1) Accessor methods: ‘get()’ method
return(age);
- Used to determine the current value of an attribute
}
2) Mutator methods: ‘set()’ method
public void setAge(int anAge) {
- Used to change an attribute (set it to a new value):
age = anAge;
}

Dr. Mohamed K. Hussein 3


Example
public class Person { public class MainClass {
private int age; public static void main(String [] args){
public Person() { Person ahmed = new Person();
age = 0;
} System.out.println(ahmed.getAge());
public int getAge() { ahmed.setAge(21);
System.out.println(ahmed.getAge());
return(age);
}
}
}
public void setAge(int anAge){
age = anAge;
}
}

Dr. Mohamed K. Hussein 4


Constructors Overloading

• Constructors are used to initialize objects

• Set the attributes as the object is created.

• Different versions of the constructor can be implemented with different

initializations

• e.g., one version sets all attributes to default values while another version sets some

attributes to the value of parameters.

Dr. Mohamed K. Hussein 5


Constructor overloading
•Method overloading, same method name, different parameter list.
public Person(int anAge) { public Person() {
age = anAge; age = 0;
} }

// Calling the versions (distinguished by parameter list)


Person p1 = new Person(100); Person p2 = new Person();

Dr. Mohamed K. Hussein 6


Example
public class Person { public Person(int anAge, String aName) {
private int age; System.out.println("Person(int,String)");
private String name; age = anAge;
name = aName;
public Person() {
}
System.out.println("Person()");
public int getAge() {
age = 0;
return(age);
name = "No-name";
}
}
public String getName() {
public Person(int anAge) {
return(name);
System.out.println("Person(int)");
}
age = anAge;
public void setAge(int anAge) {
name = "No-name";
age = anAge;
}
}
public Person(String aName) {
public void setName(String aName) {
System.out.println("Person(String)");
name = aName;
age = 0;
}
name = aName;
}
Dr. Mohamed K. Hussein 7
}
Example
public class MainClass {
public static void main(String [] args) {
Person p1 = new Person(); // age, name default
Person p2 = new Person(21); // age=21
Person p3 = new Person(“person_3"); // name=“person_3”
Person p44 = new Person(65,"person4"); // age=65, name = “person_4”
System.out.println(p1.getAge() + " " + p1.getName());
System.out.println(p2.getAge() + " " + p2.getName());
System.out.println(p3.getAge() + " " + p3.getName());
System.out.println(p4.getAge() + " " + p4.getName());
}
Dr. Mohamed K. Hussein 8
}
Method signatures
• Method signatures consist of: the type, number and order of the parameters.

• The signature will determine the overloaded method called:

Person p1 = new Person();

Person p2 = new Person(25);

Dr. Mohamed K. Hussein 9


Private Keyword
• It syntactically means this part of the class cannot be accessed outside of the
class definition.

• You should always do this for variable attributes, very rarely do this for
methods.

• Example public class MainClass {


public class Person { public static void main(String [] args) {
private int age; Person aPerson = new Person();
public Person() { aPerson.age = 12;
// Syntax error: program won’t compile!
age = 12;
}
//OK – access allowed here
}
}
Dr. Mohamed K. Hussein 10
}
Encapsulation/Information Hiding
•Protects the inner-workings (data) of a class.
get data set data
•Only allow access to the core of an object in a (accessor (mutator
method) method)
controlled fashion (use the public parts to
public public public
access the private sections). method method method

- Typically it means public methods accessing private


data
private attributes via accessor and mutator
methods.
- Controlled access to attributes:
• Can prevent invalid states
• Reduce runtime errors Dr. Mohamed K. Hussein 11
Graphical Summary Of Classes

• UML (Unified modeling language) class diagram

• Source “Fundamentals of Object-Oriented Design in UML” by Booch, Jacobson,

Rumbaugh (Dorset House Publishing: a division of Pearson), 2000.

• UML class diagram provides a quick overview about a class

• ater, you we’ll talk about relationships between classes

Dr. Mohamed K. Hussein 12


UML Class Diagram

<Name of class> Person


-<attribute name>: <attribute type> -age:int
+<method name>(p1: p1type; p2 : p2 type..) : +getAge():int
<return type> +getFriends():Person []
+setAge(anAge:int):void

Dr. Mohamed K. Hussein 13


Attributes Vs. Locals
• Attributes • inside a class definition but outside the body of a method
public class Person {
- Declared inside a class
private String [] childrenName = new String[10];
definition but outside
private int age;
the body of a method }

• public class Person {


• Locals public getAge() {
- Declared inside the body of int data;
Scanner in = new Scanner(System.in);
a method
}

Dr. Mohamed K. Hussein 14


Scope of Attributes Vs. Locals
• Scope is the location where an identifier (attribute, local, method) may be
accessed
- Scope of attributes (and methods): anywhere inside the class definition
- Scope of locals: after the local has been declared until the end of closing brace (e.g., end of
method body)
• Example:
public class Person {
private String [] childrenName = new String[10];
private int age;

public nameFamily() { Attribute


int i; (class
for (i = 0; i < 10; i++) { scope)
Local
childrenName[i] = in.nextLine();
(method
scope) }
}
Dr. Mohamed K. Hussein 15
}
When to Use: Attributes
• Typically there is a separate attribute for each instance of a class and it lasts for
the life of the object.
class Person
{
private String [] childrenName = new String[10];
private int age;
/*
For each person it’s logical to track the age and
the names any offspring.

*/
}

Q: Life of an object?
Dr. Mohamed K. Hussein 16
When to Use: Locals
• Local variables: temporary information that will only be used inside a method
public nameFamily()
{
int i;
Scanner in = new Scanner(System.in);
for (i = 0; i < 10; i++) Scope Scope of
{
of ‘i’ ‘in’
(int) (Scanner)
childrenName[i] = in.nextLine();
}
}

• Q: Does it make sense for every ‘Person’ to have an ‘i’ and ‘in’ attribute?
Dr. Mohamed K. Hussein 17
Scoping Rules
• Rules of access
1. Look for a local (variable or constant)
2. Look for an attribute
Second: look for the
definition of an attribute
public class Person e.g., “private int x;”
{
First: look for the
public void method() definition of a local
{ identifier e.g., “int x;”

x = 12;
}
} Reference to
an identifier

Dr. Mohamed K. Hussein 18


Shadowing
• The name of a local matches the name of an attribute.
• Because of scoping rules the local identifier will ‘hide’ (shadow) access to the
attribute.
• This is a common logic error!
public class Person {
private int age = -1;
public Person(int newAge) {
int age; // Shadows/hides attribute
age = newAge;
}
public void setAge(int age) { // Shadow/hide attribute
age = age;
}
}

Person aPerson = new Person(0); // age is still -1


Dr. Mohamed K. Hussein 19
aPerson.setAge(18); // age is still -1
Addresses And References
• Real life metaphor: to determine the location that you need to reach
the ‘address’ must be stored.

???

121 122 123


123

• Think of the delivery address as something that is a ‘reference’ to Reference =


123
the location that you wish to reach.
- Lose the reference and you can’t ‘access’ (go to) the desired location.

Dr. Mohamed K. Hussein 20


Variables & Addresses

• Variables are a ‘slot’ in memory that contains ‘one piece’


of information.
num = 123

• Normally a location is accessed via the name of the


variable.
- Note however that each location is also numbered!
- This is the address of a memory location.

Dr. Mohamed K. Hussein 21


Image: Curtesy of Rob Kremer
References & Objects
public class Person • In main():
{
Person ahmed;
private int age;
public Person() { Person mariam;
age = 0;
} ahmed = new Person(20);
mariam = new Person(15);
public Person(int data) {
age = data; System.out.println(“Ahmed object age: " + ahmed.getAge());
}
mariam = ahmed;
public int getAge() {
ahmed.setAge(21);
return(age);
} System.out.println(“ahmed object name: " + ahmed.getName());
public void setAge(int data) { System.out.println(“mariam object name: " + mariam.getName());
age = data;
}
}
Dr. Mohamed K. Hussein 22
Summary

• Constructor overloading • UML


• Accessor method (“get”) • Scoping rules
• Mutator method (“set”) • Addresses and references
• Method overloading

• Method signature

• Encapsulation/information hiding
Dr. Mohamed K. Hussein 23
Assignment 2

I. Create a class called time that has:


• separate int member data for hours, minutes, and seconds.
• One constructor should initialize this data to 0,
• Another constructor initialize it to fixed values.
• Accessor & mutators methods for the attributes.
• A method to display time in 11:59:59 format.
• A method to add two objects of type time passed as arguments.
• In the main() should create two initialized time objects and one that isn’t initialized.
Then it should add the two initialized values together, leaving the result in the third
time variable. Finally, it should display the value of this third variable.
Dr. Mohamed K. Hussein 24
Assignment 2

II. Create an employee class.


• The member data should comprise an int for storing the employee
number and a float for storing the employee’s salary.

• Methods to allow the user to enter this data and display it.

• Apply constructors overloading.

• Accessor & mutators methods for the attributes.

Dr. Mohamed K. Hussein 25


Assignment 2

III. Create a date class.


• Its member data should consist of three ints: month, day, and year.

• Two member functions: getDate(), which allows the user to enter a date
in 12/31/02 format, and showDate(), which displays the date.

• Apply constructors overloading.

• Accessor & mutators methods for the attributes.

Dr. Mohamed K. Hussein 26


Thank you

You might also like