Title: Introduction to Programming
1Introduction to Programming
- Arrays and Object Orientation
- P Blanchfield
2Arrays
- We have already seen an array
- public static void main(String args)
- Declared a String array called args
- We have yet to use this
- We can have arrays of any inbuilt type
- Or any type we make ourselves
- We have to define the size of these
- For C programmers it is a little different
- For Pascal programmers we need to think
differently - You declare an array of integers like this
- int a // declares a to be an array of
integers - int b // similarly declares b both are
valid - You have to initialise the arrays before using
them - a new int4 // Initialises the array to hold
4 values - For integer the values will all be 0
- You should not rely on this
- To get at an individual value you should put
- a0 3 // set the first value in the array to
3 - d a3 // set d to the value of the fourth
element in the array
3Arrays
- Note arrays are indexed from 0 so
- double b
- b new double5
- Declares and initialises b to be an array of 5
doubles starting with b0 and going to b4
not b5 - If you reference b5 it will not cause the
compiler to fail but it would cause a run time
error - ArrayIndexOutOfBoundsException
- Look out for this
4Exercise
- Create a program called counter
- It just needs a main method
- The method should declare an array of ten
integers - The integers should be 1 10
- That is a0 1 a9 10 //etc
- Use a for loop to fill the array
- Use a second for loop to print the array in
descending order
5Objects
- Everything is an object
- But describing everything in this way is not
always the most helpful approach - However, it is a very common and important
commercial programming paradigm - Classes can describe
- Concrete objects such as things and people
- Less concrete things like expectations and
behaviours of programs - For example a response to an action can be an
object! - We never did grammar at school so we dont care
if this is a good use of the word object - I think it is OK because I can say The response
was so if I can find a way to treat it as an
object in a sentence it must have some sense
6Classes in Java
- Objects are things and classes are descriptions
of things - The attributes they have
- The behaviours they have
- How they interface to the rest of the system
7Public private and protected
- Everything can be one of these
- Attributes and functions of a class can be and so
can the class itself - If something is public anyone can see it and use
it - If something is private only the object itself
can see it and use it - If something is protected only its descendants
and members of its close family (in Javas case
things in the same package) can see it
8Public and Private
- Mostly we want to keep things about ourselves
private - Or at least protected
- But to allow us to interact with the world and
the world to interact with us we have to provide
ways to interact with the world - When we go to a conference we may wear a name
badge but we would not do this when we walk down
the street (would we?) - The way we provide name badges in Java is to have
methods that tell the world about our class and
to ask the world questions - The facts about our class are kept private and
the interacting messages are made public - We do this by placing a public keyword before the
method - We can also put a private keyword before the
private things but in Java private is the default
9Remember our Hello World
- We have seen public since our first example
- We made the main method of our Hello World
program public so it could interact with the
world - In that case it was so it could run
- From now on we are going to introduce separate
classes to describe things we want to work on
that are not already described in Java - Mostly we will make these public so that we can
reuse them easily
10Inbuilt Java Classes
- Lots of things are already Java classes
- We have met the String class
- We have met the Math class
- Other classes can be built by us
- TButills was built by Tim Brailsford
- We can build classes we can include for ourselves
11Making a new Class
- We need to introduce new classes when we have
something we can efficiently represent in our
program by an object that we do not already have - When we need to extend the functionality of
another class
12Lets Create a Simple Class
- We already know how to start
- Our earlier class already has
- A method to calculate a combination
- And a Factorial
- And a main which runs them
- But it has no attributes!
- This is most unusual
13Separating out our class
- We will separate our combination class from the
one which will have the main - The class has properties that can be set from
outside (in some way) - The number of elements
- The number to be chosen from that
- It could usefully hold the factorials of these as
internal parameters to which we provide no access
outside of the class at all - We will provide a method to calculate the
combination value - It also needs a constructor where we will set the
first two parameters
14What is a constructor?
- A constructor is a function that tells you how to
make an object of the given type - Most methods must have a return type
- Even if it is void
- Something they send back
- Even if it is nothing
- A constructor does not have a return type
- It must have the same name as the class
- There can be a number of versions of the
constructor method - If you do not specify a constructor Java will
assume a default one that does nothing - Once you have a class you can declare an object
of that type using new - What you are actually doing is invoking the
constructor
15Invoking a constructor
- You have already seen this if you have declared a
new String - String message new String(Hello)
- This is one of the versions of the constructor
- There is also the default one
- String message new String()
- This will contain an empty string
- Let us do an example for our Combinations class
16The combinations class
- We already know how to start
- Define a file called Comb.java
- Declare its contents
17public class Comb private int m, n, mCn // mCn
is the number of combinations that can be made
from m things private int fact(int a) //the
factorial of a int sum 1 for(int i 1 i
lt a i) sum i return sum
private int mCombN(int a, int b) //calculate
the number of combinations int aCb aCb
fact(a) / (fact(a - b) fact(b)) return
aCb public Comb(int a, int b) //The
constructor m a n b mCn
mCombN(m, n) public int combinations() //A
method to access the value of mCn return
mCn
18In this class
- Currently mCn, m and n are private variables
- The values of m and n are not accessible from the
outside - We probably want to add member functions to make
them accessible - We also may want to be able to set and change
them and thus recalculate mCn - The factorial and combination functions are the
same as we had before
19Using this class
- We will use this class from another class
- We could use it lots of times and from lots of
other classes in the same package - Example a program called UseComb
20UseComb
public class UseComb public static void
main(String args) private Comb comb new
Comb(5,3) System.out.println(Combinations of 5
taken 3 at a time comb.combinations())
This class is the one with the main in it It has
to have the same name as the file it is saved in.
To work this will have to be in the same folder
as the Comb class You could also put the Comb
class into this file but that must no longer be
private It would also be a less flexible way to
work Comb will have to be compiled first This
will definitely work for JCreator Using Netbeans
etc you may need to put in the package statement
at the beginning of both files
21Exercise
- What else should our class provide?
- Possibilities
- Finding out the value of m and n
- Method might be called getNumberFrom()
- getNumberBy()
- Setting a new value for m and/or n
- Might be setM(int a) and setN(int a)
- They should also recalculate mCn
- Error checking!
22Inheritance
- This is an important issue when developing groups
of classes that are similar to but not the same
as each other - Cars and motorbikes are both wheeled vehicles and
have things in common - But they are also different
- Students can be post graduate taught, post
graduate research and undergraduate but they are
all students
23The student class
- This would be the base class
- The other classes would inherit some things from
this base - And add some special characteristics of their own
- Student id and name would be in the base
- A list of classes would be in the pg taught but
not the pg r - Pg t and ug would have a tutor
- Pg r and perhaps pg t would have a supervisor
24Employee Class
- Employees have things in common and specific
things - Academic staff and non academic staff in the
University all have - payroll numbers
- Surnames (family names etc)
- First names (given names)
- Dates of employment
- Dates of birth
- Bank account details
- Academic staff have
- Subjects taught
- Research supervisions
- Tutees
25Class Inheritance
- A class of Employee can have the main parameters
of the employee - A class called Academic will inherit from this
but extend this class to give the extra
parameters - In java we do this as follows
- class Academic extends Employee
26Exercise
- Load my classes from here
- Use JCreator to compile and run this program
- Try to understand it there are 3 classes
- The Employee class
- The Academic class
- The InheritanceDemo class
- This class uses the other two
- Extend the demo with set and get methods for name
and payroll number and number of subjects taught
by an individual - Add use of these functions to your code
27super
- Note that the Academic constructor passes on
information to the Employee constructor using the
- super()
- Method
- In our example it will use the employee version
that has one parameter the name
28The String class
- Note we have used a part of the String class here
- subjects s.split(" ")
- This method spilt splits the string into an
array of String variables based on where they
have a certain character - I have a space delimited string as my parameter
for my setSubjects method - The full code for the method is
- public void setSubjects(int n, String s)
-
- subjects s.split(" ")
- numberTaught n
-
- String s contains the list of subjects taught by
the academic and divided by space characters - In the example program it contains the string
- G64ICP G51ISS
- When called by the main routine on the academic
peter - The result of the split will be two strings
subjects0 containing G64ICP and subjects1
containing G51ISS
29The String class
- There are many other methods in the String class
- We already saw you can get at a given character
in the string of characters stored in the String
object using - charAt(index)
- Some have tried to compare two String objects in
the lab using - if(inches q)
- This does not work
- A String is an object not just a set of
characters - What you are actually asking is if the address
where the String inches is kept is the same as
the one where q is and the answer is always
false - You could do two things
- Use charAt and compare with the character q
- if(inches.charAt(0) q)
- This will return true if the first character
stored in the String inches is a q - Alternatively you can use the string comparison
functions provided by the String class - if(inches.equals(q))
- This will only return true if the string
contained in inches is q - You can also use
- equalsIgnoreCase
- So you could compare it to q and Q in one
comparison
30More on String
- Can be found in a refernce
- Some useful parts
- compareTo(otherString)
- Returns gt0 if the string comes after the other
string, lt0 if the string comes before and 0 if
they are the same (so could be used instead of
equals) - length()
- Tells you the length of the string
- toLowerCase()
- toUpperCase()
- trim()
- Removes leading and trailing space
- substring(i,j)
- Returns the string starting at I and j characters
long - Have fun