Object Oriented Programming
Object Oriented Programming
Object Oriented Programming
Source program: you compile it produce class file and this can
API: a large collection of useful “components” grouped into libraries called packages
Lowest layer: OS
On top of that: Java virtual machine where program can run on
Applet: a small java program running inside a webpage: not very popular anymore
Browser
Abstraction: taking away unimportant details: keeping only “interesting” characteristics including operations
o From different perspectives/ depending on application: you keep different characteristics
Function is already a kind of abstraction: we abstract the behaviour
Abstract data type (ADT): a set of objects + a set of operations (with NO implementation details)
Abstraction: take important characteristics
Encapsulation: hide implementation details
OOP so code is easier to read and can reuse
C++ supports encapsulation using class
OOP: people using your program doesn’t realise if implementation has changed as long as it gives same
interface
Static variable: variable is associated with the class not the variable
class classname
Data
(Member Variables)
Operations
(Methods)
Java Class:
private and public and access specifiers (access modifier)
whereas static is a lifetime specifier (lifetime modifier)
o means variable or method marked as such is available at the class level. In other words, don’t need to
create an instance of the class to access it.
Creation of an object consists of 3 phases:
o 1) Declaration (inform compiler the type of object to be referenced by the variable)
o 2) Instantiation (allocate memory for a new object using the “new operator”): eg. Student tmchan =
new Student();
o 3) Initialisation: set initial values
eg.
Student tmchan; //Declaration: class_name variable_name; (store reference of a Student obj)
Tmchan = new Student(); // instantiation: variable_name = new class_name();
//and combining these would give us Student tmchan = newStudent();
tmchan = new Student (“T.M. Chan”, 0);
//initialization: using constructors to initialize objects; specifier class_name(para_list){…..};
//where Student is the constructor // public Student(String str, int x){name = str; mark = x;}
Constructors:
Name overloading: more than one constructor can be provided if the parameter lists are different (no of
arguments or type of variables are different)
If constructor is provided, default constructor is not provided
Specifiers control which class can call the constructor
Shows visibility
Similar to C++ apart from last one
NOTE these specifiers are referring to specifiers to constructors
o private : No other class can create instances of this class using constructor
o protected : only subclasses can create instances of this class using constructor
o public : any class can create instances of this class using constructor
o (default) : package (a collection of classes): every class within the same package can access
Note: package Student (int x);
o The specifier “package” is not required
When you use an object, you need the object variable, new operator and constructor
Accessing variable
You can access variables inside using notation ‘dot’ : .
Or you can call corresponding function using . notation
In C++ there are always 2 ways to declare object
o You can declare either object or a pointer to an object
o For Student class
o Student S; // object
o Student *PS ; // pointer to an object
o When you declare pointer to an object you only have so-called reference to object and not the object
itself
But in Java, NOT POINTER NOTATION
o Always need to call new operator in Java while in C++ you can declare an object
o Most modern programming in OOP, need to destroy an object
In C++ need to use delete operator
Java, there is automatic garbage collector: manages
If there’s object no longer being referenced
Automatic garbage collector collects garage space
Don’t need to worry about these memory
Java class
Format:
specifier class class_name
{
//constructor(s); // can have multiple
//variables //
//methods //
//cleanup, finalize()// NOTE: you can do a cleanup but in normal practice you don’t define it cos we use
automatic garbage collector I mean you can define it but you don’t need to.
}
eg.
XX.count = 0;
XX.fl(…);
Static methods
Perform class-wide operations and don’t apply to individual object
class Employee {
String name;
long salary;
short employee_id;
static int total_employee;
static void clear() { total_employee = 0; }
}
Employee.clear();
Creating an array
array_name = new type [array_size];
int[] temp;
temp = new int[10];
…
temp[0] = 5;
So to create 10 student objects, you do it for each one (eg. by using for loop)
When will you use integer primitive and Integer class?
When you want to create an object then you use integer class
Initialising an array
Whenever you create an object in Java, you ALWAYS need to use
o new operator + a constructor
these objects are ALWAYS in the heap
Student[] sa;
sa = new Student[10]; // sa.length == 10
.
.
.
sa[]
go over arrays in ppt to see if you missed anything
check the array size and stuff
mentioned attribute: string? or array for main function
ask what
temp[2] = new Integer (2) ; means does it mean integer is value 2??
String:
o A sequence of characters
o Member of java.lang package
o Similar to array of characters
A string literal is 0 or more characters enclosed in double quotes
Eg.
String str = new String (“This is an example ”);
When you call constructor String,
For string you can use function “equals” to check if two strings are equal
Are s1 & s2 equal to each other
Go ova the powerpoint slidessss
String concatenation
Inheritance:
Can we find similarities between classes?
o If yes, we can put these in the base class
o Eg. rotate function in classes such as Square, Circle, Triangle, Amoeba
In OOP we look at the data we’re trying to process instead of processes
Eg. let’s look at zoos
So start by looking at the animals: eg. lions, hippos, tigers etc
Questions to ask are:
o What do they have in common? And how are they related?
most important part in database is the storage of data
data in program vs data in database: difference is
o the duration the data lasts: persistence (persistence of data)
o eg. bank account: they save your data in the database
So back to the zoo, look at relationship among the data
1. What do they have in common abstract out behaviours
2. How are they related? define the inheritance tree relationships
Important part of OOP is abstraction
Then we use a class
There are two parts in a class:
o The common state (instance variables)
o Behaviour (methods)
Eg. students: we have info on name, year blah blah these info is called the state information
Behaviour: say we want to state your marks (an action to state) methods
So back to the zoo!
Common variables
o Eg. picture: JPEG file of animal
o Food: type of food animal eats
o Hunger: int representing hunger level of animal
o Boundaries: values representing the height and width of the space the animal will roam
o Location: the (X,Y) coordinate of the animal
Common methods:
o makeNoise()
o eat()
o sleep()
o roam()
Now we look at the relationship:
So decide if a subclass needs behaviours (method implementations) that are specific to that particular
subclass type
In the animal hierarchy:
o eat() and makeNoise() are overridden so that each animal can define its own way of eat() and
makeNoise()
o All animals share the same sleep() and roam()
Look for more opportunities to
Putting everything together: now finish the class hierarchy
So in the animal hierarchy:
o Canines use a common roam()
o Now update these notes from slides
What method is called?
In ppt on What method is called?
o Canines actually use their own way of roaming
o Look at how methods are used
o So basically for w.eat: where w is wolf,
o w.eat can find method eat in class Wolf
o find w.roam: can’t find it in class wolf so goes up to canine class which you can find
o then you keep going up
Java supports single inheritance which means every class can have only one parent where c++ supports
multiple parents (so in C++ a bit more complicated because which method to use if both class has the
same methods?!)
Superclass & Subclass
Subclasses automatically contain (“inherit”) variables & methods defined in the superclass
Inheritance Hierarchy: too deep isn’t good because this will make it overcomplicated
Superclass is class’ direct ancestor AND all its ancestors
in programming, when you design data, there’s two types of relationships
o “Is A” vs “Has A” relationship
o C “Is A” D – means class C is a specialization of class D (inheritance)
o C “Has A” D – means class D is a component (part) of class C (composition, nested class)
Whereas Car, Vehicle: Is A
Computer, CPU: Has A
Private variable: variable that is only visible in a class
Subclass will inherit ALL variables and methods from superclasses, but can only access following
members of its superclasses
o Public +
o Protected +
o Package (if in the same package)
Stack Class
Subclass of vector that implements a standard last-in first-out stack
Stack has all methods defined by vector + several of its own
o boolean empty()
tests if stack is empty. Returns true if it is and false if not
o Object peek()
Returns element at top of stack but doesn’t remove it
o Object pop()
Returns element on the top of the stack and removes it in the process
o Object push(Object element)
Pushes the element onto the stack. Element is also returned
o int search(object element)
searches element in the stack
if found, its offset from the top of the stack is returned. Otherwise, -1 is returned