Nothing Special   »   [go: up one dir, main page]

Lecture03 Annotated

Download as pdf or txt
Download as pdf or txt
You are on page 1of 59

COE 318

Introduction to Software Design


Lecture 03

Dr. Naimul Khan


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 methods to
have the same name, but different
signatures (number of input params, type of
params)
Method Overloading
• Overloading: varying return type does not
qualify, parameters must be different!
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
• 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() {
return name;
}
public boolean isMale() {
return isMale;
}
}
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;
isMale = x;
}
public String getName() {
return name;
}
public boolean isMale() {
return isMale;
}
}
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;
}
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;
}
public String getRegistration() {
return registration;
}
}
Constructors

• Has the same name as the class


• Does not return a value. It has no return
type, not even void.
Constructors
• You do not have to define a constructor for
a class. Only when you would like to assign
initial values to instance variable of each
created object, you need to design a
constructor in the class.
• If a class has no constructor, the compiler
generates a default constructor with no
arguments for the class.
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
• However, if a class DOES have a
Constructor, the default constructor with no
arguments is not generated anymore.
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
• Consturctors 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(); 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 { Is this code correct?
public static void main(String[] args){
Car truck;
truck=new Car("ABC", 50);
}
}
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; FIND OUTPUT
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);}
Cube() {
length = 10;
breadth = 10;
height = 10;}
Cube(int l, int b, int h) {
length = l;
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;
}
}
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
– Parameters (of methods)
– Local variables
public class C {
private int i; //instance variable
public void f(int j) { //j is a parameter
int k; //k is a local variable
k = 2*j;
i = i + k;
}
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
• 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)

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=40, count=30;
float result1= total/count;
System.out.println(result1);
float result = (float) total / count;
System.out.println(result);
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.
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 { public class CarTest {
String licensePlate;
double speed; public static void main(String[] args) {
double maxSpeed; Car car1 = new Car("ABC",20,100); }
double fuel;
public Car(String plateNumber, double }
speedVal, double maxVal){
licensePlate=plateNumber;
speed=speedVal;
maxSpeed=maxVal;
}
}

"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.
Garbage collection
• 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.
• Garbage collection relieves the programmer
from the responsibility of releasing
dynamically allocated heap memory.
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;
Garbage
v 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;
}
public Car(){
}
}
public class CarTest {
public static void main(String[] args){
Car miniVan;
miniVan=new Car("ABC", 50, 100); Which object will be
Car sedan = new Car();
sedan=miniVan; Garbage collected after
}
} 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];

int [] scores = new int[10];

int scores[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];


System.out.println( integerArray[ 3 ]);
System.out.println( alias[ 3 ] );
}
}
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).
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;
}}}
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