Вы находитесь на странице: 1из 8

 Java: it is platform independent

 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

 Object oriented programming


 Instance is another word for object
 Things an object knows is called instance variables: represents object’s state (data) and can have unique
values for each object of that type
 Things an object can do are called methods
 A class is a blueprint for an object: tells machine how to make an object of that type
 Usually to create and use an object, we have 2 classes: one class for the type of object you want to use and
another to test your class
Java 01 oop
 Java technology = programming language + platform
 Java applications are typically compiled to bytecode that can run on any java virtual machine (JVM)
regardless of computer architecture
 JVM is a program which allows execution of other programs
 Its function is to allow Java programs to run on any device or OS and to manage and optimize program
memory
 From another powerpoint:
 A virtual machine (VM) is an abstract computer architecture
 It’s software on top of a real hardware
 Can run the same application on different machine where the VM is available
 An abstract computing machine that executes bytecode programs
o An instruction set and the meaning of those instructions: the bytecodes (bytecodes are Java binary
codes) (binary code: code using 2-symbol system)
o A binary format: the class file format
o An algorithm to verify the class file
 JVM is an runtime environment for Java
 Its implementation is not defined
 It runs Java .class files
 And has to conform to Sun’s specification
 Java virtual machine, implementation of Java Virtual Machine Specification
 Java Platform = Java VM + Java API
 An API (application programming interface) is a large collection of useful “components” grouped into libraries
(called packages). So by components, we mean a set of routines, protocols and tools for building software
applications. So an API basically specifies how software components should interact. Additionally, APIs are
used when programming graphical user interface (GUI) components
 API and VM insulate Java programs
 To use a java class:
o 1) Applications: use as a standalone program invoked in the command line
o 2) or Applets: designed to be included in an HTML page. When you use a Java-enabled browser to
view an HTML page that contains an applet, the applet’s code is transferred to your system and is run
by the browser’s Java virtual machine (but not popular anymore)
o In the powerpoint slide 9 and 11 includes how to use these
 Object-Oriented Programming (OOP)
o 4 key principles:
o Abstraction
o Encapsulation
o Inheritance
o Polymorphism

 Objects have state (instance variables) and behaviour (methods)


 Class: a blueprint for an object: it tell JVM how you should make an object of that type
 Every object of that type can have different instance variable values
 A method uses parameters. A caller passes arguments
 This is good
o https://beginnersbook.com/2013/03/oops-in-java-encapsulation-inheritance-polymorphism-
abstraction/
 Abstraction:
o Displaying only essential information and hiding details
o It keeps only interesting characteristics (these interesting characteristics also include operations)
o Provides only essential information about the data to the outside world and hiding the background
details or implementation
 ADT: abstract data type
o a set of objects + a set of operations (with no implementation details)
 Encapsulation:
o Users access data (including implementation) and operations implementation through a set of
interface
o This data (+ implementation) and operations implementation is treated as a whole unit
o Encapsulation is defined as binding together the data and the functions that manipulates them
together
o The whole idea behind encapsulation is to hide the implementation details from users
o Encapsulation is about hiding complexity
o The reason for doing this is to provide a simplified and understandable way to use your object without
the need to understand the complexity inside
 C++ supports encapsulation using class
o Class is an abstraction of a group of objects: an object is an instance of the class
o It is implementation independent: people using your program doesn’t realise if implementation has
changed as long as it gives same interface
 A structure of a Java program has eg.
Eg.
class A

class B

class XX

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.
}

 Similar to constructor, other specifiers:


 Class can have following specifiers:
 You always need at least one public class for each package
o default (class is default mode if no specifier is mentioned): can be used in classes within the same
package
o public: can be used by any classes
o abstract: this class cannot be instantiated (will visit later)
o final: cannot be inherited (to avoid subclasses to be defined(security reasons)) (will visit later in
notes)

 Per-Instance and Per-Class Members in Java


 In a “normal” class definition, fields and methods are defined and each object has its own version of members
 “static” variables: used if only one copy of member is needed
o only one copy will be kept
 “static” methods
o other “static” stuffs exist but these two are the most common (if interested see notes p34 I think?)
 use of static members: accessing directly through class name
 eg.
Class XX {
static public int count;
static public void fl(…);
}

eg.
XX.count = 0;
XX.fl(…);

 Access by CLASS NAME not by object

 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();

 NOTE: main() is always a static method

 Primitive and reference data types


 Reference is like a pointer but no pointers in Java
 Primitive:
o Integers: byte (8 bits), short (16 bits) , int (32 bits), long (64 bits)
o Real: float (32 bits), double (64 bits)
o Others: char (16 bits), Boolean (true or false)
 Reference:
o Array and class
 All primitive data type start with lower case: eg. int, Boolean
 All classes have capital letter: Student tmchan;
 Every primitive type has a corresponding reference class (will talk more later)
 the corresponding classes in java.lang to primitive data type
o Eg. Integer and int
o Boolean and Boolean
o Byte and byte
o Float and float
o Long and long
 Reference class of corresponding data type provides lots of functions: reason why it exists

 Static: a decoration about life time specifier


o can be declared for variable or function
o if for function  that function is associated to a class
o same for variable  that particular variable associated to a class
o when you create object, there are variables
 but if a variable is declared as static, this variable isn’t associated with an object but the class
 think of it as a global variable
o static function
 one of it is the main: the main is always static
 this is because when you start running a program you don’t have any objects
 belongs to the class rather than object of the class
 can be invoked without need for creating an instance of a class
 static method can access static data member and can change value of it
 if you don’t delete object in c++ , memory used by object can’t be reclaimed
 in Java, when you declare object
o declaration : telling compiler the type of object to be referenced by the variable
o instantiation: allocating memory: allocating memory for a new object using “new” operator
 an object in C++  can calculate it
 but in Java you don’t know: Virtual machine will allocate for you
 Java reserves enough memory for new object
 Eg. variable_name = new class_name();
 NOTE that new is an operator NOT a function
 Call new along with constructor
o Initialization: set initial values
 Call constructor:
o In Java, if you don’t call constructor, compiler will call default
o Default does nothing but it allocates memory for you
o Initialisation: can use constructor to initialize objects:
o Can provide parameters to constructor
o Don’t need return value for constructor
 Every primitive data type in in Java

 Variables declared within a block { } only exists within the block


 Static scoping: can see use of variable by studying program
 Dynamic scoping: understand variable by watching program run
 Recap: In Java, one of main difference with C++
o In C++ you can define object variable or object pointer
o No such thing in Java
 In Java,
o NO SUCH THING AS AN OBJECT VARIABLE
o In Java there are no pointers
o Declaring an object  you’re declaring an object reference variable: it acts like a pointer
 Quoting the ppt, it says : object reference variable holds bits that represent a way to access
an object, like a pointer (except the internal structure of a reference variable is not defined)
 That’s why we have to use the new operator to allocate memory, cos otherwise it’s just a
reference and no memory is allocated to it
o Object reference variable: holds bits that represent a way to access an object like a pointer
 In JVM, there is a “heap”: sometimes called garbage collectible heap  there to hold memory space for
objects
 Say we created a book object using new operator and book constructor: if you create an object, it’ll always be
in the heap
 If variable is pointing at nothing (NULL), called “garbage”
 Java Language Constructs
o && : and operator
o <<
o >>
o >>> look up
o instanceof operator
 Control Flow Statements: same as C++
 For loop: used for counting (going to terminate) as opposed to while loop (if programme not correct, then can
go into infinite loop)
 Class definition:
 Programme always starts at main method
 public static void main (String[] args) {
…..;
}
  main function always has a parameter
 String always has one attribute: length
 When you run a class as an application and supply arguments to it, it will supply an array of strings as the
arguments
 They are stored as reference to the parameters
 Args is an array of strings
 To declare an array:
type [ ] name;
eg. int [ ] intarray = new int [10];
 always need to call new constructor and size of array
 Java array:
o Sequence of data of the same type (class)!
o When you declare array in Java, similar to C++
 Difference is you DON’T NEED TO SPECIFY SIZE
 Until you call the constructor which then needs to say size
o When you declare array variable, only gives you memory location of the array
int[] temp;
temp[0] = 4;
 gives runtime error cos no memory allocated to array yet

 Creating an array
array_name = new type [array_size];
int[] temp;
temp = new int[10];

temp[0] = 5;

 Student[] stud_array = new Student[10];


 Only allocate 10 memory locations for storing 10 references in entries of stud_array
 This code creates an array of NULL no objects of class Student are created yet

Student[] stud_array = new Student[10];


stud_array[0] = new Student() ;
stud_array[0].name = “T.M. Chan”;

 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,

 Say you have objects that are the same con

 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

Вам также может понравиться