• No results found

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

N/A
N/A
Protected

Academic year: 2021

Share "CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5"

Copied!
10
0
0

Loading.... (view fulltext now)

Full text

(1)

CS1002: COMPUTER SCIENCE

OO MODELLING & DESIGN: WEEK 5

School  of  Computer  Science   University  of  St  Andrews    

Graham  Kirby   Alan  Dearle  

http://www.rodgersleask.co.uk/images/sc2.jpg  

This Week

§  More  on  Java  classes  

§  Constructors  

§  Modifiers  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   2  

cdn.videogum.com/img/thumbnails/photos/commenter.jpg  

Fields and Variables

§  A  field:  

ú  has  a  type  and  identifier  

ú  holds  information  relevant  to  object  of  specific  class   ú  is  defined  in  class  

ú  exists  as  long  as  the  object  does  

§  A  variable:  

ú  has  a  type  and  identifier  

ú  holds  temporary  information  relevant  to  method  execution     ú  is  defined  in  method  

ú  exists  only  while  method  is  being  executed  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   3  

W05 Example 1: Variables & Fields

public class C { private int a = 2;

public void m() { int b = 7;

b = 16;

a = -9;

} }

public class D {

public static void main(String[] args) { C obj = new C();

obj.m();

} }

CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5  

variable  update   field  declaration   variable  declaration  

4  

©  University  of  St  Andrews  2011/12  

Code   example   1  

field  update  

object  creation  

method  call  

(2)

Memory States

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   5  

public class C { private int a = 2;

public void m() { int b = 7;

b = 16;

a = -9;

} }

public class D {

public static void main(String[] args) { C obj = new C();

obj.m();

}

}

W05 Example 2: Variable Scope

public class C { public void m1() { int i = 32;

System.out.println("i: " + i);

}

public void m2() { i = i - 3;

} }

CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5  

this  is  illegal:  i  is  out  of  scope   variable  i  is  created  here...  

...  and  disappears  again  here  

6  

©  University  of  St  Andrews  2011/12  

Code   example   2  

W05 Example 3: Method Calls

public class C { public void m1() {

C another_one = new C();

another_one.m2();

this.m2();

m2();

}         public void m2() { ...

} }

public class D {

public static void main(String[] args) { C obj = new C();

obj.m1();

} }

method  call  on  a  different  object   method  calls  on  this  object  

Code   example   3  

Memory States

public class C { public void m1() { C another_one = new C();

another_one.m2();

this.m2();

m2();

}

public void m2() { ...

} }

public class D {

public static void main(String[]

args) {

C obj = new C();

obj.m1();

}

}

(3)

Method Parameters

§  Methods  take  parameters:  

ú  information  passed  to  the  method  when  it's  called,  to  tell  it   specifically  what  to  do  

ú  each  parameter  is  treated  like  a  variable  within  the   method  body  

   equivalent  to  a  variable  containing  the  value  specified  by  the   caller  of  the  method  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   9  

W05 EXAMPLE 4: METHOD PARAMETERS

Code   example   4   www.coolingtower-­‐profiler.com/robo_kran.jpg  

Parameter and Field Names

§  Sometimes  convenient  to  use  fields  and  parameters   with  the  same  names:  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   11  

Code   example   5  

public class C { int salary = 0;

public void setSalary(int salary) { salary = salary;

} }

public class D {

public static void main(String[] args) { C obj = new C();

obj.setSalary(400);

System.out.println("obj.salary = " + obj.salary);

} }

the  parameter   the  parameter  

the  field   Doesn’t   do  what   you  want  

Distinguishing Parameters and Fields

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   12  

Code   example   6  

public class C { int salary = 0;

public void setSalary(int salary) { this.salary = salary;

} }

public class D {

public static void main(String[] args) { C obj = new C();

obj.setSalary(400);

System.out.println("obj.salary = " + obj.salary);

} }

the  parameter  value   the  field  

the  field  

(4)

Constructors

§  We  may  wish  to  ensure  that  new  objects  of  a   particular  class  are  always  initialised  in  a  certain  way  

Student s = new Student();

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   13  

Constructors cont'd

§  A  constructor  is  like  a  special  method  that  is   executed  when  an  object  is  created  

ú  can  initialise  the  object  in  any     required  way  

ú  can  take  parameters,  like  method   ú  doesn't  return  any  result  

ú  always  has  the  same  name  as     the  class  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   14  

supercolossal.ch/blog/skynet_high%20speed%20constructor.png  

W05 Example 7: Single Constructor

public Student(String name, String id) { this.name = name;

this.id = id;

year = 2004;

}

§  Can  now  create  student  object  with  

Student s = new Student("Jane Jones", "040412716");

Code   example   7  

Test Class

§  Can  put  code  in  Test  class  to  test  other  class  implementation  e.g.  

ú  instantiate  student  object  with  name  and  id   ú  print  out  the  details  of  the  student  object   public class Test {

public static void main(String[] args) {

Student s = new Student("Jane", "040412716");

s.printDetails();

}

}

(5)

Multiple Constructors

§  May  want  several  different  ways  to  initialise  objects  

ú  can  have  more  than  one  constructor  in  a  class   ú  but  they  must  all  take  different  parameters  –  why?  

§  Use  

Student s1 = new Student("Jane Jones", 040412716");

Student s2 = new Student();

Student s3 = new Student("Jane Jones");

§  Example  of  overloading  

ú  the  identifier  of  the  constructor  refers  to  different  bits  of  code   depending  on  the  number  and  type  of  its  arguments  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   17  

W05 EXAMPLE 8: MULTIPLE CONSTRUCTORS

Code   example   8  

www.activoinc.com/blog/wp-­‐content/uploads/2009/06/overload_cargo.jpg  

Default Constructor

§  Simple  constructor  defined  automatically  if  we  don’t   write  any  

ú  just  creates  instance  and  fills  in  default  attribute  values   ú  equivalent  to,  for  example:  

public Student() { this.name = null;

this.id = null;

this.year = 0;

}

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   19  

Linking Constructors

§  So  we  have  seen  

ú  a  class  can  have  multiple  constructors   ú  distinguished  by  different  parameters  

§  May  want  to  call  one  constructor  from  another,  to   avoid  duplicating  code  

ú  use  this  keyword  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   20  

(6)

W05 EXAMPLE 9: LINKED CONSTRUCTORS

Code   example   9  

Method Overloading

§  We  have  seen  multiple  constructors  with  the  same     names  but  different  parameters  

ú  can  also  do  the  same  with  other  methods  

ú  only  do  this  when  the  methods  are  closely  related  in   purpose...  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   22  

Code   example   10  

Encapsulation

§  An  object’s  field  values  are  (should  be)  encapsulated  

ú  they  can’t  be  seen  directly  by  other  objects   ú  but  can  be  accessed  by  that  object’s  methods  

§  Benefits  

ú  improves  control  over  how  field  values  are  read  and   updated  

ú  helpful  in  structuring  software  

   can  change  one  part  without  affecting  others  

Encapsulated Objects

“Alan Dearle”

“Graham Kirby”

(7)

Getters and Setters

§  So,  may  need  to  write  methods  for  each  class  that  allow     other  objects  to  access  its  fields  

§  Accessor  methods:  

ú  set  the  content  of  a  field  to  a  certain  value  (setter)   ú  return  the  value  held  in  a  field  (getter)  

§  Provides  standardised  access  to  fields  by    

ú  other  parts  of  your  program  (other  classes)   ú  other  programmers  when  using  your  code  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   25  

Code   example   11  

Visibility and Other Modifiers

§  Some  modifiers:  

ú  public,  private,  protected,     static,  final  

§  Apply  to  classes  and     other  members:  

ú  fields,  methods,  constructors  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   26  

www.arteworks.biz/phamilton/uploaded_images/long-­‐tail-­‐modifiers-­‐774652.jpg  

public Modifier

§  Modifier  for  classes,  fields,  methods,  constructors  

ú  means  that  class  or  member  can  be  accessed  from  anywhere   ú  no  restrictions:  

   class  can  be  instantiated      field  can  be  read  or  updated      method  can  be  called      constructor  can  be  called  

public class Person { public String name;

public int getAge(){...}

public Person(String s) {...}

}

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   27  

private Modifier

§  Modifier  for  fields,  methods,  constructors  

ú  means  that  member  can't  be  accessed  from  anywhere  outside  the  class   ú  restrictions:  

   field  can't  be  read  or  updated      method  can't  be  called      constructor  can't  be  called  

public class Person { private String name;

private int getAge(); ...

private Person(String s); ...

}

ú  the  normal  modifier  for  fields  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   28  

(8)

protected Modifier

§  Modifier  for  fields,  methods,  constructors  

ú  means  that  member  can  be  accessed  only  from  the   defining  class  or  another  class  in  the  same  package   public class Person {

protected String name;

protected int getAge(); ...

protected Person(String s); ...

}

ú  the  default  if  you  don't  write  any  visibility  modifier  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   29  

static Modifier

§  Modifier  for  fields  and  methods  

ú  means  that  member  is  associated  with  class  as  a  whole   rather  than  individual  object  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   30  

Static Fields

§  Fields  can  belong  to  an  instance  of  the  class  (object)   or  to  all  instances  (objects)  of  the  class  

§  For  non-­‐static  fields  there  is  a  memory  slot  inside   every  object  of  a  certain  class  

§  For  static  fields  there  is  a  single  memory  slot  which   pertains  to  the  whole  class  

§  Need  to  decide  which  is  sensible...  

W05 EXAMPLE 12: STATIC FIELD

Code   example   12  

www.tyhen.com/images/StaticField.jpg  

(9)

Static Fields cont’d

§  Static  fields  can  be  referred  to  from  outside  a  class   (subject  to  visibility)  using  the  class  name,  e.g.  

Person.number_of_people  

§  Within  the  class,  they  can  be  referred  to  just  like  non-­‐

static  fields  i.e.  without  the  class  name  prefix  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   33  

Static Methods

§  Methods  can  also  be  declared  static  

ú  already  seen  this  with  main  method:  

public static void main(String[] args){…}

 

§  Only  makes  sense  when  method  doesn’t  have  anything   to  do  with  any  particular  instance  of  the  class,  e.g.  

public static int getTotalPeople(){

return number_of_people;

}

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   34  

Static Methods cont’d

§  Static  methods  can  also  be  referred  to  from  outside  a   class  using  the  class  name,  e.g.  

int count = Person.getTotalPeople();

double x = Math.sin(0.6);

String string_rep = String.valueOf(4.251);  

 

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   35  

Rule

§  A  static  thing  can't  access  a  non-­‐static  thing  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   36  

code  in  a  static  method  

code  initialising  a  static  field   a  non-­‐static  field  

a  non-­‐static  method  

(10)

final Modifier

§  The  static  keyword  is  perhaps  confusing  

ú  suggests  that  the  value  of  the  field  cannot  change  

§  Use  final  keyword  to  declare  a  field  to  be  constant  

ú  once  a  value  has  been  assigned  to  it,  it  cannot  be  changed    

public static final int MAX_ARRAY_SIZE = 100;

private static final String PROMPT = "enter int";

final int x = y + z;

§  Modifier  applies  to  methods  too  

ú  we'll  see  later  what  this  means  (to  do  with  inheritance)  

©  University  of  St  Andrews  2011/12   CS1002  Computer  Science  -­‐  OO  Modelling  &  Design  -­‐  Week  5   37  

References

Related documents

Shah Deniz Gas Field: project in 4 stages, with EBRD total senior loans of USD 220 million to partly finance Lukoil and SOCAR 20% share in consortium SCP Pipeline: project in

More specif- ically, this thesis contains the first applications of proof mining to the theory of partial differential equations and moreover to the theory of accretive, set-

the ministries established a Corporate Value Study Group composed of legal experts and business representatives to consider an appropriate policy response to hostile

s = read_from_network(); −→ untrusted source syslog(s); −→ trusting sink. Format

On the issue of whether s 8 violates the right of an accused person to a fair trial, protected in s 35(3) of the Constitution, the court held that ‘accused person’ may not

Four dimensions of HRM practices namely, training and development; career development; salary and benefit; and performance appraisal; along with five dimensions of

When your child is ready for solid food, ready-made baby meals can seem like the best option, however, making it yourself can be more economical, healthier and fun.. The good

Conclusions: Although invasive lobular carcinomas comprise 12% of all female breast cancers, they are very rare in males due to lack of acini and lobules in the normal male