Lecture 03 Annotated - Classes and Object P2 - Variables
Lecture 03 Annotated - Classes and Object P2 - Variables
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)
}
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;
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
Primitive Non-Primitive
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;
"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);
}