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

Lecture 03 Annotated - Classes and Object P2 - Variables

Uploaded by

kemalemran25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Lecture 03 Annotated - Classes and Object P2 - Variables

Uploaded by

kemalemran25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

COE 318

Software Systems
Lecture 03:
Classes and Object P2
Variables

Boujemaa Guermazi
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public void setLicensePlate(String plateNumber ){
licensePlate=plateNumber;
}
/*……………….
Code from lecture 2 goes here
………………*/
}
Method Overloading
Overloading allows different add(int a, int b)
methods to have the same name,
add(int a, int b, int c)
but different signatures (number
of input params, type of params). add(double a, int b)

add (int[] numbers)


Method Overloading
Overloading: varying return type does not
qualify, parameters must be different!

int add(int a, int b)

double add(int a, int b)


Modify the Car class
Add a method accelerate() that increases
speed.
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public void setLicensePlate(String plateNumber ){
licensePlate=plateNumber;
}
/*……………….
Code from lecture 2 goes here
………………*/
public void accelerate(){
speed=speed+10;
}
}
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public void setLicensePlate(String plateNumber ){
licensePlate=plateNumber;
}
/*……………….
Code from lecture 2 goes here
………………*/
public void accelerate(){
speed=speed+10;
}
public void accelerate(double amount){
speed=speed+amount;
}
}
Method overloading
• Note that both accelerate() methods have
the same name, but different parameters.

• This would have been illegal in C.


Mutable vs Immutable class
• An immutable class is one whose state cannot be
modified after it is instantiated.
– Immutable object: You can’t change the object’s state
after you’ve created it.
• A mutable class is one whose state can be modified
after it is instantiated.
– Mutable objects: allow their state to be changed.
Mutable vs Immutable class
• In our Car class, we have getter and setter methods
for all the instance variables. This is a mutable class
(object state can be changed after creation).
• Although that makes it easy to set or get the variable
values, that is something you may not always want.
What if a malicious code tries to change license
plate, or set speed to a sudden high value?
Mutable vs. Immutable class
One alternative is to allow to set the instance variables
ONLY during creation, can’t change them after
creation.
→ That will make the Car class Immutable.
Our current example of Car class is actually very
difficult to make immutable, since instance variables
like speed, fuel has to be changed after creation.
An example immutable class
public class Person {
private String name;
private boolean isMale;
public String getName() { ✓Mark instance
return name; variables private.
}
public boolean isMale() {
return isMale; ✓Mark getters and
}
}
setters public.
How to set the values of name
and isMale?
public class Person {
private String name;
private boolean isMale;
public String getName() {
return name;
}
public boolean isMale() {
return isMale;
}
}
Use a Constructor
public class Person {
private String name;
private boolean isMale;
public Person(String n, boolean x) {
name = n; A constructor is runs before the
isMale = x;
} object can be assigned to a reference.
public String getName() {
return name;
} → That means you get a chance to
public boolean isMale() {
return isMale; step in and do things to get the object
}
} ready for use.
Is this class immutable?
public class Voter {
private String registration;
private String name;
public String getName() {
return name;
}
public String getRegistration() {
return registration;
}
public void setRegistration(String reg) {

}
registration=reg;
No
public void setName(String n) {
name=n;
}
}
Is this class immutable?
public class Voter {
private String registration;
private String name;
public Voter(String reg, name n){
registration=reg;
name=n;
}
public String getName() {
return name;
} yes
public String getRegistration() {
return registration;
}
}
Constructors
• The only way to invoke a constructor is with
the keyword ‘new’ followed by the class name
• It has the same name as the class
• It does not return a value. It has no return
type, not even void.
Invoke a constructor
public class Person {
private String name;
private boolean isMale;

public Person(String n, boolean x) {


name = n; public class UsePerson {
isMale = x;
} Public static void main (String[ ] args) {
public String getName() { Person Pers1 = new Person ("John", true);
return name; }
}
}
public boolean isMale() {
return isMale;
}
}
Why do you need to write a constructor if the compiler
writes one for you?

• If a class has no constructor, the compiler generates a


default constructor with no arguments for the class.

- If you need code to help initialize your object and get it


ready for use, you’ll have to write your own constructor.
Example: You might be dependent on input from the
user before you can finish making the object ready.
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public Car(String plateNumber, double speedVal, double maxVal){
licensePlate = plateNumber;
speed = speedVal;
maxSpeed = maxVal;
}
}
public class CarTest {
public static void main(String[] args){
Car miniVan;
miniVan=new Car("ABC", 50, 100);
}
}
Constructors
• If a class does have a constructor, the compiler will
not automatically generate the default no-argument
constructor.

So, if you write a constructor that takes arguments


but still want a no-arg constructor, you'll have to write
it yourself!
public class Car {
String licensePlate; What will happen?
double speed;
double maxSpeed;
double fuel;
public Car(String plateNumber, double speedVal, double maxVal){
licensePlate=plateNumber;
speed=speedVal;
maxSpeed=maxVal;
}
}
public class CarTest {
public static void main(String[] args){
Car miniVan;
miniVan=new Car("ABC", 50, 100);
Car sedan = new Car();
}
}
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public Car(String plateNumber, double speedVal, double maxVal){
licensePlate=plateNumber;
speed=speedVal;
maxSpeed=maxVal;
}
}
public class CarTest {
public static void main(String[] args){
Car miniVan;
miniVan=new Car("ABC", 50, 100);
}
Car sedan = new Car(); Error, won't compile
}
Constructors
Constructors can be overloaded too, you can
have multiple Constructors!
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public Car(String plateNumber, double speedVal, double maxVal){
licensePlate=plateNumber;
speed=speedVal;
maxSpeed=maxVal;
}
public Car(){
}
}

public class CarTest {


public static void main(String[] args){
Car miniVan;
miniVan=new Car("ABC", 50, 100);
Car sedan = new Car();
}
}
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public Car(String plateNumber, double speedVal, double maxVal){
licensePlate=plateNumber;
speed=speedVal;
maxSpeed=maxVal;
}
public Car(){
}
}

public class CarTest {


public static void main(String[] args){
Car miniVan;
miniVan=new Car("ABC", 50, 100);
}
Car sedan = new Car(); Fixed!
}
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public Car(String plateNumber, double speedVal, double maxVal){
licensePlate=plateNumber;
speed=speedVal;
maxSpeed=maxVal;
}
public Car(){
}
}

public class CarTest {


public static void main(String[] args){ Is this code correct?
Car truck;
truck=new Car("ABC", “50”, 100);
} No: “50” IS STRING
}
public class DefaultConstructorOnly {
int size = 5;
}
public class DefaultConstructorOnly {
int size = 5;
}

public class OneConstructor {


OneConstructor(String message) {
System.out.println(message);}
}
public class DefaultConstructorOnly {
int size = 5;
}

public class OneConstructor {


OneConstructor(String message) {
System.out.println(message);}
}
public class TwoConstructors {
TwoConstructors(String message) {
System.out.println(message);}
TwoConstructors() {
System.out.println("No argument Constructor");
}
}
public class DefaultConstructorOnly {
int size = 5;
}

public class OneConstructor {


OneConstructor(String message) {
System.out.println(message);}
}
public class TwoConstructors {
TwoConstructors(String message) {
System.out.println(message);}
TwoConstructors() {
System.out.println("No argument Constructor");
}
}

public class Constructors {


public static void main(String args[]) {
DefaultConstructorOnly ok = new defaultConstructorOnly();
TwoConstructors alsoOk = new TwoConstructors();
OneConstructor okToo = new OneConstructor();
}
}
public class DefaultConstructorOnly {
int size = 5;
}

public class OneConstructor {


OneConstructor(String message) {
System.out.println(message);}
}
public class TwoConstructors {
TwoConstructors(String message) {
System.out.println(message);}
TwoConstructors() {
System.out.println("No argument Constructor");
}
}

public class Constructors {


public static void main(String args[]) {
DefaultConstructorOnly ok = new defaultConstructorOnly();
TwoConstructors alsoOk = new TwoConstructors();
OneConstructor compileError = new OneConstructor();
}
}
public class Cube {
int length;
int breadth; FIND OUTPUT
int height;
public int getVolume() {
return (length * breadth * height);}
Cube() {
length = 10;
leng br height
breadth = 10;
height = 10;}
CubeObj1→ 10 10 10 →1000
Cube(int l, int b, int h) {
length = l;
CubeObj1→ 10 20 20 →6000
breadth = b;
height = h;}
public static void main(String[] args) {
Cube cubeObj1, cubeObj2;
cubeObj1 = new Cube();
cubeObj2 = new Cube(10, 20, 30);
System.out.println("Volume of Cube1 is:" + cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume()); }}
The "this" keyword
• “this” refers to current object.
→ When a method is called, it is automatically passed
an implicit argument that is a reference to the
current invoking object (that is, the object on which
the method is called). This reference is called this.
• Writing the statement without using this is really
just shorthand.
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public Car(String plateNumber, double speedVal, double maxVal){
licensePlate=plateNumber;
speed=speedVal;
maxSpeed=maxVal;
}
}
Equivalent Code
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public Car(String plateNumber, double speedVal, double maxVal){
this.licensePlate=plateNumber;
this.speed=speedVal;
this.maxSpeed=maxVal;
}
}
Now, the same instance variable names can be used for the
parameters for clarity, without conflict (common practice in Java)
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public Car(String licensePlate, double speed, double maxSpeed){
this.licensePlate= licensePlate;
this.speed= speed;
this.maxSpeed= maxSpeed;
}
}
Variables
variables
To use a variable in a program you need to perform 2 steps:
– Variable Declaration
– Variable Initialization
variables
To use a variable in a program you need to perform 2 steps:
– Variable Declaration
– Variable Initialization

Type Name

double fuel;
variables
To use a variable in a program you to need to perform 2 steps:
– Variable Declaration
– Variable Initialization
Container naimed
fuel holding a value
150 type double

fuel = 150 ; 150.0


variables
You can combine the 2 steps,
variable declaration and initialization. Container naimed
fuel holding a value
150 type double

double fuel = 150 ; 150.0


Types of variables
• Based on data type:
– Primitives (int a, short b etc).
– Reference variables. Any data of type object. (Car
miniVan, String name etc)
Data Type

Primitive Non-Primitive

Boolean Numeric Car

String
Integral Character

Integer Float
boolean (byte, short, int, long) (float, double) char Array …
Types of variables
• Based on data type:
– Primitives (int a, short b etc).
– Reference variables. Any data of type object.
(Car miniVan, String name etc)
• Based on usage:
– Instance variables
– Local variables variables are declared within a method
– Parameters (methods arguments)
public class C {
private int i; //instance variable
public void f(int j) { //j is a parameter
int k; //k is a local variable
int m; //m is a local variable
k = 2*j;
i = i + k + m;
}
public void g() {
int k; //another local variable named k
}
}
Class as "data type"?
• Once you define a class, it just becomes a "data type".

→You can declare variables as the class type e.g. Car sedan;

• You can have methods return the class type

e.g. public Car giveMeaCar()

• Can be parameter type in a method

e.g. public boolean isSameSpeed(Car a, Car b)


Example
public class Car {
…..
…..
public boolean isSameSpeed(Car a, Car b){
if(a.getSpeed()==b.getSpeed()){
return true;
}
return false;
}
}
Conversion between primitive types
• Widening conversions : from a small data type to
a larger one.

byte → short → int → long → float → double


Conversion between primitive types
• Narrowing conversions: Can lose information
because they tend to go from a large data type to a
smaller one (such as an int to a short)

double → float→long →int →short → byte


Widening conversions
class Car {
// Main driver method
public static void main(String[] args)
{
int fuel = 150;

// Automatic type conversion


// Integer to long type
long fuelAmount = fuel;
Casting
• Both types of conversions can be achieved
by explicitly casting a value.
• To cast the type is put in parentheses in
front of the value being converted.
int total, count;
float result = (float) total / count;
int total1 = (int) result;
Casting
Casting is a must when dividing integers by integers
and you want a floating point. Without casting, result
will throw out the numbers after decimal point.
int total=45, count=30;
float result1= total/count;
System.out.println(result1); →1
float result = (float) total / count;
System.out.println(result); → 1.5
In the incomplete code for next slide:
A. Fill in code for the constructor. (Calculate the GPA as
totalGradePoints / totalHours.)

B. Fill in code for getGPA()

C. Write code in the main method that will create a student


object with the following initial data: "Sanders, Bruce",
35, 92. Print out the GPA of this new student.
class Student {
private String name; // In the form "LastName, FirstName"
private int totalHours; // total number of hours completed
private int totalGradePoints; // GPA = totalGradePoints / totalHours
private double GPA; // grade point average
//uses name, totalHours, and totalGradepoints as parameters
public Student(String name, int totalHours, int totalGradePoints) {
// Fill in for Part a.
}
public double getGPA() { // return the GPA, fill in for part b.
}
public static void main (String[] args){
//fill in for part c.
}
}
class Student {
private String name; // In the form "LastName, FirstName"
private int totalHours; // total number of hours completed
private int totalGradePoints; // GPA = totalGradePoints / totalHours
private double GPA; // grade point average
//uses name, totalHours, and totalGradepoints as parameters
public Student(String name, int totalHours, int totalGradePoints) {
// Fill in for Part a.
this.name = name;
this.totalGradePoints = totalGradePoints;
this.totalHours = totalHours;
GPA = (double)totalGradePoints / totalHours; // Notice the casting!
}
public double getGPA() { // return the GPA, fill in for part b.
return GPA;
}
public static void main (String[] args){
//fill in for part c.
Student bSanders = new Student("Sanders, Bruce", 35, 92);
System.out.println(bSanders.getGPA());
}
}
Variable initialization
• Local variables are not automatically initialized;
using them before they are set causes a
compilation error.
• Instance variables are automatically initialized to 0
(for numbers), the character '\0' for chars and null
for references.
null (a keyword in Java) can represent a reference to
any type of object.
public class Example {
private int num;
private char letter;
private String text;
private double value;

public static void main(String[] args) {


Example example = new Example();
System.out.println("num: " + example.num);
System.out.println("letter: " + example.letter);
System.out.println("text: " + example.text);
System.out.println("value: " + example.value);
}
}
public class Example {
private int num; // Initialized to 0
private char letter; // Initialized to '\u0000' (null character)
private String text; // Initialized to null (reference to no object)
private double value; // Initialized to 0.0

public static void main(String[] args) {


Example example = new Example(); // Create an instance of Example
System.out.println("num: " + example.num); // Output: num: 0
System.out.println("letter: " + example.letter); // Output: letter:
System.out.println("text: " + example.text); // Output: text: null
System.out.println("value: " + example.value); // Output: value: 0.0
}
}
Data storage in memory
• Primitive variables have their own size
(e.g. int require 4 bytes).
• Reference variables : The variable itself
require 4 bytes (or 8 bytes on a 64-bit
machine) + any memory required for the
instance variables of the object.
Data storage in memory - heap
• Any memory required
by an object goes into
the special section of
the memory called the
heap.
Data storage in memory - stack
• Local variables and
parameters, however,
reside elsewhere: on
a data structure that
can grow and shrink
dynamically called
the Stack.
Heap vs. Stack
public class Car {
String licensePlate; public class CarTest {
double speed;
double maxSpeed; public static void main(String[] args) {
double fuel;
public Car(String plateNumber, double speedVal, double maxVal){ Car car1 = new Car("ABC",20,100); }
licensePlate=plateNumber;
speed=speedVal; }
}
maxSpeed=maxVal;
Car car1
}

"ABC"
20
car1 100
Stack Heap
Variable lifetime
• When a method is invoked, the parameters are first
pushed onto the stack. When the method is entered,
additional space on the stack is reserved for all local
variables. The method's code is then executed.
• When the method finishes, it releases the space on
the stack occupied by its local variables and
parameters automatically: they no longer exist.
A stack scenario
public void performTask() {
boolean b = true;
process(4);
}

public void process(int x) {


int z = x + 24;
execute();
// imagine more code here
}

public void execute() {


char c = 'a';
}
Garbage collection
• Garbage collection relieves the programmer from the
responsibility of releasing dynamically allocated heap
memory.
• To manage heap memory, Java maintains a reference count
of how many reference variables point to it.
• Reference count drops to zero → the object is eligible for
garbage collection which reclaims the heap space used by
the object.
Reference variable and assignment
• When you assign one reference variable to another reference
variable, the second variable begins to reference the object
the first reference variable is referencing to.
v = minivan; //both v & minivan are of Car class
→ After this assignment, object v will reference the memory
that object minivan references to.
Reference variable and assignment
• When you assign one reference variable to another reference
variable, the second variable begins to reference the object
the first reference variable is referencing to.
v = minivan; //both v & minivan are of Car class
→ After this assignment, object v will reference the memory
that object minivan references to.
What happens to the memory block the v referenced to before
the assignment?
Reference variable and assignment
• When you assign one reference variable to another reference
variable, the second variable begins to reference the object
the first reference variable is referencing to.
v = minivan; //both v & minivan are of Car class
→ After this assignment, object v will reference the memory
that object minivan references to.
What happens to the memory block the v referenced to before
the assignment?
If no more object variables reference to it, it will be collected by
the garbage collector.
Illustration of reference variable
assignment
v Heap
minivan Memory
Stack
v=minivan;
v Garbage
collected
minivan
Stack
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public Car(String plateNumber, double speedVal, double maxVal){
licensePlate=plateNumber;
speed=speedVal;
maxSpeed=maxVal; X
}
public Car(){
}
}
public class CarTest {
public static void main(String[] args){ Which object will be
Car miniVan;
miniVan=new Car("ABC", 50, 100);
Car sedan = new Car();
Garbage collected after
}
sedan=miniVan; execution of this line?
}
Arrays
• An array stores multiple values of the same type.
• That type can be primitive types or objects
• Array of size N is indexed from zero to N-1.
Declaring Arrays
int [] scores;
scores=new int[10];
Declaring Arrays
int [] scores;
scores=new int[10];

int [] scores = new int[10];


Initializing Arrays
int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476};
char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};
Accessing Array elements
int scores[3];
scores[0] = 79;
scores[1] = 87;
scores[2] = 92;
mean = (scores[0] + scores[1]+scores[2])/3;
System.out.println ("Average = " + mean);
Accessing Array elements
int scores[3];
scores[0] = 79;
scores[1] = 87;
scores[2] = 92;
mean = (scores[0] + scores[1]+scores[2])/3;
System.out.println ("Average = " + mean);

• An index used in an array reference must specify a valid element.


• The index value must be in bounds (0 to N-1), where N is the length
• Java interpreter throws an ArrayIndexOutOfBoundsException
error if an array index is out of bounds.
The length property
• Each array object has a public constant called length
that stores the size of the array.
public class Primes
{
public static void main (String[] args)
{
int [] primeNums = {2, 3, 5, 7, 11, 13, 17, 19};
System.out.println ("Array length: " + primeNums.length);
for (int i=0; i< primeNums.length; i++)
System.out.println (primeNums[i]);
}
}
Arrays in memory
public class ArrayExamples
{
public static void main( String args[] ) {
int integerArray[ ];
int[ ] alias;
integerArray = new int[5];
for ( int index = 0; index < integerArray.length; index++ )
integerArray[ index ] = 5;
alias = integerArray;
alias[3] = 10;
System.out.println( integerArray[ 3 ]);
integerArray = new int[3]; 10
System.out.println( integerArray[ 3 ]);
System.out.println( alias[ 3 ] ); Error → IndexOutOfBounds
}
} 10
Arrays of objects
• The elements of an array can be objects themselves.
• When an array is created, memory is NOT
automatically allocated for the objects.
• Each array element will have to be individually
allocated memory explicitly (initially contains null).
FIND OUTPUT
Class Books {
String title;
String author;
}
class BooksTestDrive {
public static void main (String [] args) {
Books [] myBooks = new Books[2];
int x=0;
myBooks[0] = new Books();
myBooks[1] = new Books();
myBooks[0].title = “The Grapes of Java ”;
myBooks[0].author = “bob”;
myBooks[1].title = “The Java Gatsby ”;
myBooks[1].author = “sue”;
While (x<2) {
System.out.print (myBook[x].title);
System.out.print (“ by ”);
System.out.println (myBooks [x].author);
}}}
x = x+1;
The Grapes of Java by bob
The Java Gatsby by sue
FIND OUTPUT
class HeapQuiz {
int id = 0;}
class HeapQuizTest{
public static void main (String [] args) {
int x = 0;
HeapQuiz [] hq = new HeapQuiz[5];
while (x < 3) {
hq[x] = new HeapQuiz();
hq[x].id = x;
x =x +1; }
hq[3] =hq[1];
hq[4] =hq[1];
hq[3] =hq[2];
for (int j=0; j<5; j++)
System.out.println ("hq["+j +"]:"+hq[j].id);
}
}
}

You might also like