0% found this document useful (0 votes)
2 views

lect03-week2

The document provides an overview of arrays in Java, detailing the steps for declaration, construction, and initialization, along with examples of how to work with arrays and object arrays. It also covers Java data types, the differences between primitive and reference types, and the principles of object-oriented programming, including abstraction, encapsulation, and access control. Additionally, it includes naming conventions and examples of encapsulation and abstraction in class design.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

lect03-week2

The document provides an overview of arrays in Java, detailing the steps for declaration, construction, and initialization, along with examples of how to work with arrays and object arrays. It also covers Java data types, the differences between primitive and reference types, and the principles of object-oriented programming, including abstraction, encapsulation, and access control. Additionally, it includes naming conventions and examples of encapsulation and abstraction in class design.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Programming2(CS272)

Lecture 3

1ncap
Arrays in JAVA

To create and use an array, you must follow three steps:


1. Declaration
2. Construction
3. Initialization ( giving initial values to array elements)

1.Declaration
null
int [] x; x
BankAccount [] accounts;
accounts null

▪Square brackets can be placed either before or after array name.


public static void main (String [] args) Or public static void main (String args [] )

Declaration never state size


int [3] x : compile error
2
2. Construction
Using new an array is constructed (the array is an object),
In construction you state the size of array
Array elements are automatically initialized to their default values.
Length of array can be accessed by arrayname.length; ex : x.length
int [] x; //Declaration System.out.println(x.length); //prints 3
x=new int [3];// construction

int [] z=new int [10]; // declaration & construction


BankAccount [] accounts=new BankAccount[3]; // declaration & construction

0 x[2] null accounts[2]


x 0 x[1] accounts null accounts[1]
0 x[0] null accounts[0]

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};
}
}

N.B : java allows an array to be returned from a method


Public int [] m() { …….}
Array of Objects
Arrays can hold a certain type of objects

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.

Primitive 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

public static void sort(int[] a)

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

Abstraction Encapsulation Association Polymorphism

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 Person{ class Course{


String name; String code;
Date birth; int numOfStudents;
…. ….
boolean isAdult() boolean isFull()
{….} {….}
…. ….
} }
15
Example 1 : Abstraction of a Credit Card
public class CreditCard{
double limit;
int number; Misuse of
double balance; class
static final double MAX_LIMIT=20000; class Test{
public CreditCard(int number){ public static void main (String [] arg){
this.number=number; CreditCard card1=new CreditCard(345);
} 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.buyWithCredit(15000);
} }
public boolean buyWithCredit(double amount){ }
if ((balance+amount)>limit) return false;
balance=balance+amount;
return true;}
public void creditSettle(double amount){ WRONG
balance=balance-amount; Limit >MAX_LIMIT using
} card1.limit=100000;
} setLimit must be used 16
Encapsulation
I. A language construct that facilitates the bundling of data with the methods operating
on that data (this is achieved using the class structure)
II. A language mechanism for restricting access to some of the object's components, (this
is achieved using access modifiers)
A class should encapsulate only one idea , i.e. a class should be cohesive
Your Encapsulation design should minimize dependency in order to ensure that there is a
loose-coupling
allows you to make internal changes
to a class without affecting any code
that calls the class. This reduces
coupling, or how much any given
class relies on the implementation
of another class.

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

Instance variables are declared private to


prevent misuse.
providing methods that can be used to public class Person{
read/write the state rather than private int age;
accessing the state directly. public void setAge(int age ){
if (age<0)
{
System.out.println("unaccepted value");
Person p1=new Person();
return;
p1.age=10;
}
System.out.println(p1.age);
this.age=age;
}
public int getAge(){
Person p1=new Person(); return age;
p1.setAge(10); }
}

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

• Design and implement a class called Car that


contains instance data that represents the
make, model, and year of the car (as a String,
String and int values respectively). Define the
Car constructor to initialize these values (in
that order).
• Include getter and setter methods for all
instance data

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

Add a default empty no-arg constructor to initalize member variables


Add a constructor for instance variable initialization using arguments
24
Access Control
Java provides several modifiers that control access to data fields, methods, and classes

• public makes classes, methods, and data fields


accessible from any class.
• private makes methods and data fields accessible public int i;
private double j;
only from within its own class. public void m (){}
• If no access modifier is used, then by default the int x;
classes, methods, and data fields are accessible
by any class in the same package. This is known as
package-access.
• If protected is used, then that member can be
accessed by own class and classes from same
package and from subclass outside the package .

The default constructor has the same access as its class


Local Variables can not have an access modifier
25
The Different Levels of Access Control
private default protected public Visibility
Yes Yes Yes Yes From the same class
No Yes Yes Yes From any class in the same package
No No No Yes From any class outside the package
No Yes Yes Yes From a subclass in the same package
From a subclass outside the same
No No Yes Yes
package

Access modifiers apply to class members (variables and methods) and constructors too.

Class D,E subclasses of


class C

26
The four OOP Principles

Abstraction Encapsulation Association Polymorphism

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...

Customer purchase Book


A customer can purchase a book

One way of implementation is by having object as a method argument

public class Book public class Customer


{ {
private double price ….
double getPrice() void purchase(Book book)
{ {
book.getPrice();
} //////
}
} …..
} 28
Example Association by passing objects as arguments
public class Customer{
public class Book{ private double purchaseAmount;
private double price; public void purchase(Book book)
private String title; {
public Book(double price, String title) purchaseAmount +=book.getPrice();
{ }
this.price=price; public double getPurchaseAmount()
this.title=title; {
} return purchaseAmount ;
public double getPrice() }
{ }
return price;
} public class Main{
public String getTitle() public static void main(String [] args){
{ Customer cutomer1=new Customer ();
return title; Book book1=new Book(100,”Java”);
} Book book2=new Book(200,“C#”);
} cutomer1. purchase(book1);
cutomer1. purchase(book2);
System.out.println(cutomer1.getPurchaseAmount());
}
29
}
Aggregation
Aggregation is a type of association.
A connection between two objects where one has a field that refers to the other.
Aggregation is referred to as weak has a.
has a relationship is implemented by the having object as member variables
The lifetime of objects are not associated
Aggregation is a kind of association that specifies a whole/part relationship between the
“A person has a lawyer “
aggregate (whole) and component part.
class Person class Lawyer
{ {
public void sue()

} }
“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(){} }
}

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

The CoffeeTable owns 4Leg A house owns a room

public class Car


public class Engine {
{ Engine e;
} e=new Engine();
}

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

You might also like