lect03-week2
lect03-week2
Lecture 3
1ncap
Arrays in JAVA
1.Declaration
null
int [] x; x
BankAccount [] accounts;
accounts null
3
3.intialization
Initialization is done by giving initial values to array elements
Declaration ,construction and initialization can also be in one line
int [] x={1,2,5};
Example 0 x[2]
int [ ] x;// declaration 0
X=new int [3];//construction
x x[1]
X[0]=5;//initialization 5 x[0]
Example:-
class Test
{
public static void main (String [] arg)
{
int [] x=new int[10];
x[0]=9;x[4]=7;
int [] y={10,2,7};
}
}
class Test{
class BankAccount
Public static void main (String [] arg){
int accountNum;
BankAccount [] accounts=new BankAccount[3];
int accountBalance;
accounts[0]=new BankAccount(); //initialization
String customerName;
accounts[1]=new BankAccount(223,1000,”Ahmed”);
BankAccount(int num, int
}}
balance, String name)
{
accountNum=num; null accounts[2]
accountBalance=balance; accounts accontNum=223
customerName=name;
accountBalance=1000
} customerName=“Ahmed” accounts[1]
BankAccount()
{ accontNum=0
}} accountBalance=0 accounts[0]
customerName=null
5
JAVA Data Types
Java data types are either primitive Data types or Reference data types.
boolean-char-byte
short-int-long-float-do
uble
class A interface B
{ {
} }
class Test{
A a1;
B b1;
int [] arr;
Int x;
}
The value of a reference variable is a reference (a pointer) to the actual value or set of
6
values represented by the variable.
JAVA Data
• Key difference between Types…………
primitive and reference data types is how
they are represented
• Primitive type variables hold the actual value of the variable
• Reference type variables hold the value of a reference to the
object
class A
int i;
int j;
A(int i,int j)
{
this.i=i;
this.j=j;
}
x 7 }
i=5
a1 int x=7
j=10 A a1=new A(5,10);
Example :Dealing with references
class Box{ box1
double width;
double height;
double depth; width=2.0
width=0.0
Box(){} height=0.0
height=4.0
Box(double w,double h,double d){ depth=0.0
depth=6.0
width=w;
height=h;
depth=d;} box2
width=4.0
double getVolume(){ height=10.0
double volume=width*height*depth; depth=12.0
//double vol=this.width*this.height*this.depth; depth=14.0
return volume;
}
}
box3
class BoxDemo{
public static void main (String [] arg){
Box box1=new Box();
box1.width=2;box1.height=4;box1.width=6;
Box box2 = new Box(4,10,12); 8
Box box3 = box2;
box3.depth=14;
System.out.println(box2.depth);
}}
Passing Primitive data types to methods
when you pass a primitive data type to a method, it is passed by value.
What occurs to the parameter that receives the argument has no effect outside the
method.
class Employee{
int salary;
public Employee(int salary){
this.salary=salary;
}
}
public class Test
{
public static void raiseSalary(int salary)
{
salary=salary+100;
}
public static void main(String args[]) {
Employee emp1 = new Employee(1000);
System.out.println("salary before call: " + emp1.salary );
int money=emp1.salary;
raiseSalary(money);
1000
System.out.println("salary after call: " + money );
}}
9
Passing references to Methods
Reference to objects can be passed to methods , and usually the method can use this
reference to access the methods and variables declared in the class of the object
class Circle
{ public class TestPassObject {
private double radius; public static void main(String[] args) {
Circle(double radius) Circle myCircle = new Circle(5.0);
{ printCircle(myCircle);
this.radius=radius; }
} public static void printCircle(Circle c)
public double getRadius() {
{ System.out.println("The area of the circle of radius "
return radius; + c.getRadius() + " is " + c.getArea());
} }
public double getArea() }
{
return 3.14*radius*radius;
}
}
10
Passing references to
Methods…………
When you pass a reference data type to a method, the value of parameter in method will
be equal to the value of reference .
changes made to the parameter will affect the argument used to call the method.
class Employee{
Salary=1000
Salary=1100
int salary;
public Employee(int salary){
this.salary=salary;
}
} emp1
emp
class Test{
public static void raiseSalary(Employee emp){
emp.salary=emp.salary+100;
}
public static void main(String args[]) {
Employee emp1 = new Employee(1000);
System.out.println("salary before call: " + emp1.salary );
raiseSalary(emp1);
System.out.println("salary after call: " + emp1.salary );
}}
11
Example :Passing an array as a reference
java.util .Arrays
import java.util.Arrays;
class Test
{
public static void main (String [] arg)
{
int [] x={7, 3,9,1};
Arrays.sort(x);
for (int i=0;i<x.length;i++){
System.out.println ("x["+i+"]="+x[i]);
}
}
}
12
JAVA Naming Conventions
Examples Rules for Naming Identifier
Type
class Bank Class names should be nouns, in mixed case Classes
class BankAccounts with the first letter of each internal word capitalized.
()run Methods should be verbs, in mixed case with the first letter Methods
()runFast lowercase, with the first letter of each internal word
capitalized.
int i; Nouns in mixed case with a lowercase first letter. Internal Variables
float myWidth; words start with capital letters.
Variable names should be short yet meaningful.
One-character variable names should be avoided except for
temporary “throwaway” variables.
Common names for temporary variables are i, j, k,m, and n
for integers; c, d, and e for characters.
int MIN_WIDTH = 4 Nouns all uppercase with words separated by underscore Constants
(“_”).
package util; Noun, lowercase Package
13
The four OOP Principles
Object-Oriented Relationships
Association UML symbol
Aggregation : has a
Composition: owns a
Inheritance : is a
Implementation : provides a
14
Abstraction
• Abstractions is formed by reducing the information content of a
concept typically to retain only information which is relevant for
a particular purpose
• Abstraction design : abstraction reduce and factor out details so
that one can focus on a few concepts.
• Abstraction allows the design stage to be separated from the
implementation stage of the software development.
class AutoTransmission
{
private int valves;
void shiftGear()
{……………….}
17
}
Better Encapsulation of class CreditCard
public class CreditCard{
private double limit;
private int number;
private double balance; class Test{
public static double fimal MAX_LIMIT=2000; public static void main (String [] arg){
public CreditCard(int number){ CreditCard card1=new CreditCard(345);
this.number=number; card1.setLimit(5000);
} card1.buyWithCredit(500);
public void setLimit(double limit){ card1.buyWithCredit(1500);
If(limit<=MAX_LIMIT) card1.limit=100000;
this.limit=limit; Card1.setLimit(100000);
else return; card1.buyWithCredit(15000);//return false
} }
public boolean buyWithCredit(double amount){ }
if ((balance+amount)>limit) return false;
balance=balance+amount;
return true;
}
public void creditSettle(double amount){
balance=balance-amount;
}}
18
Encapsulation
19
Data Field Encapsulation
20
Data Field Encapsulation
public class Person{
Instance variables are declared private to private int age;
prevent misuse. private String name;
providing methods that can be used to private boolean adult;
read/write the state rather than public int getAge()
accessing the state directly. {return age;}
public void setAge(int age )
Accessors and mutators {this.age=age;}
public String getName()
• Accessor method (getters): a method that {return name;}
provides access to the state of an object to be public void setName(String name)
accessed. {this.name=name;}
A get method signature: public boolean isAdult()
public returnType getPropertyName() {return adult;}
If the returnType is boolean : public void setAdult(boolean adult)
public boolean isPropertyName() {this.adult=adult;}
• Mutator method(setters): a method that modifies
an object's state. }
A set method signature:
public void setPropertyName(dataType propertyValue)
21
Example :Class Car
22
public class Car {
private String make, model;
private int year;
public Car(String make, String model, int year) {
setMake(make);
setModel(model);
setYear(year);
}
public String getMake() {return make;}
public void setMake(String make) {this.make = make;}
public String getModel() {return model;}
public void setModel(String model) {this. model = model;}
public int getYear() {return year;}
public void setYear(int year){this.year=year;}
}
23
Example : Abstraction of a Product
-: private
+:public
# :protected
Access modifiers apply to class members (variables and methods) and constructors too.
26
The four OOP Principles
Object-Oriented Relationships
Association UML symbol
Aggregation : has a
Composition: owns a
Inheritance : is a
Implementation : provides a
27
Implementing Object-Oriented Relationships : Association
• association defines a relationship between classes of objects which allows
one object instance to cause another to perform an action on its behalf...
} }
“A department has a
professor“
public class Person{ class Test
private Lawyer lawyer; {
Person (Lawyer lawyer){ ….
this.lawyer=lawyer;} Lawyer mylawyer=new Lawyer ();
void m(){ Person p1=new Person(myLawyer);
lawyer.sue() Person p2=new Person(myLawyer);
} p1.m();
30
} }
UML Representation for Aggregation
public class A {
public class B {
private B [] b1;
private int y;
private int x;
public void m2(){}
public void m1(){}
}
}
31
Composition
• A composition is a strong type of aggregation.
• Each component in a composite can belong to just one whole.
• Composition defines the relation “owns a” / “part-of' relationship”/” strong has a”
• The lifetime of objects are associated
32
Case Study : Voting System
Design a software for a simple voting system using 2 classes :class Voting & class Citizen
Each Voting has a title and variables representing accept count (acceptCount) and refuse count
(refuseCount)
Each object of class Voting is initialized using the title of the Voting .
Class Voting has the following methods :
accessor method for the title, acceptCount and the refuseCount fields.
method incrementAcceptCount() : increase the accept count for the Voting
method incrementRefuseCount (): increase the refuse count of the Voting
method boolean checkAcceptance () : if the accept counts are more than the refused count
return true otherwise return false
33
Case Study : Voting System
Design a software for a simple voting system using 2 classes :class Voting & class Citizen
Each citizen has a name and a boolean field (eligible)representing whether he is eligible to vote
or not , each citizen also has a Voting.
Each object of class citizen is initialized using the name of citizen and the Voting .
Class Citizen has the following methods :
accessor and mutator methods for eligible field.
accessor method for the name field.
method voteFor() : check eligibility and then increase the accept count for the Voting .
method voteAgainst(): check eligibility and increase the refuse count of the Voting .
( a citizen can vote only once)
34
35
public class Voting public boolean checkAcceptance()
{ {
private int acceptCount; if (acceptCount>refuseCount)
private int refuseCount; return true;
private String title; else
public Voting(String title) return false;
{ }
this.title=title;
} public int getAcceptCount()
public String getTitle() {
{ return acceptCount;
return title; }
} public int getRefuseCount()
public void incrementAcceptCount() {
{ return refuseCount;
acceptCount++; }
} }
public void incrementRefuseCount()
{
refuseCount++;
}
36
public class Citizen public void voteAgainst()
{ {
private String name; if(eligible)
private boolean eligible; vote.incrementRefuseCount();
private Voting vote; eligible=false;
}
public Citizen(String name,Voting vote)
{ public String getName()
this.name=name; {
this.vote=vote; return name;
} }
public void setEligible(boolean eligible)
{ public boolean isEligible()
this.eligible=eligible; {
} return eligible;
public void voteFor() }
{ }
if(eligible)
vote.incrementAcceptCount();
eligible=false;
}
37
import javax.swing.JOptionPane;
class VoteTest
{
public static void main (String [] arg)
{
Voting vote1=new Voting("Presdintal Vote");
Citizen c1=new Citizen("Ahmed Hussien",vote1);
Citizen c2=new Citizen("Akrum Ahmed",vote1);
Citizen c3=new Citizen("Ahmed Moamed",vote1);
c1.setEligible(true);
c2.setEligible(true);
c3.setEligible(true);
c1.voteFor();
c2.voteFor();
c3.voteAgainst();
System.out.println ("Accept Count :"+vote1.getAcceptCount());
System.out.println ("Refuse Count :"+vote1.getRefuseCount());
boolean flag=vote1.checkAcceptance();
if (flag)
JOptionPane.showMessageDialog(null, "Candidate Accepted!");
else
JOptionPane.showMessageDialog(null, "Candidate Refused!");
}
}
38