SWEN20003-无代写
时间:2024-02-11
SWEN20003-OOSD
期末复习资料
内容预览
1. A Quick Tour of Java
2. Classes and Objects
3. Object-Oriented Design paradigms
4. Java Package
5. Arrays and Strings
6. Input and Output
7. Inheritance
8. Interface
9. Modelling (UML)
10. Generics
11. Collections and Maps
12. Design Patterns
13. Exceptions
14. Testing and Design
15. Even-Driven Programming
16. Advanced Java
MELBOURNE
TUTOR: Eason 2023 Semester 2
sds
2
一、Quick Tour of Java
Java language/ program:
- Is compiled and interpreted
- Is platform-independent and Portable
- Is an Object-Oriented Programming OOP language
Java compiler:
- converts java source code (.java) to bytecode (.class)
- bytecode is close to machine representation
Java Interpreter (virtual machine):
- on any target platform interprets the bytecode.
- Porting to any new platform involves writing an interpreter.
- will figure out the equivalent machine dependent code to run.
Java programs:
- Application: stand-alone, has main method, can invoked using Java interpreter.
- Applet: can embedded in web, no main method, can run in (java enabled) web browser
Build Java programs:
- import: used to import additional classes, import java.lang.* is optional because it is default
Java identifier (naming):
- must not start with a digit
- cannot be Java keywords or reserved words, such as Object/ Class
- are case-sensitive.
- all the characters must be letters, digits, or the underscore symbol
- variables, methods: start with a lower-case letter, boundaries with an uppercase letter.
- class: start with an upper-case letter, boundaries with an uppercase letter.
3
- constant: All in upper case, boundaries with an under line.
Java primitive data type:
- A unit of information that contains only data
- has not attribute and methods
- only include, byte, short, int, long, float, double, char, boolean
- float with single precision must append f or F, 2.3f or 2.3F
- byte, short, int, long, float, double with default value 0
- char with default value empty char (‘’) not space.
- boolean with default value false
Non-primitive (Derived) data type:
- Class, Array, Interface, Object, String, Wrapper Class
Java variable:
- has a memory location and an identifier
- Instance variable: inside class, maintain the state of object, one copy per object
- Local variable: inside a method or defined in a method, as opposed to the instance variable
- Static/Class variable: share among all objects of the class, one copy per class.
- Final: can only declare once
- Constant: A value that does not change during the execution of the program, read only.
Java Operator:
- Arithmetic Operators: +, -, *, /, %
- Relational Operators: <, =, >, <=, >=, ==, !=
- Logical Operators: &&, ||, !
- Bitwise (Rarely used): &, |, ^, ~, <<, >>, >>>
- Condition Operator: exp1 ? exp2: exp3 (same as if condition)
- Other Operator: ++ (+= 1), -- (-= 1)
4
Java flow control:
- Refers to branching and looping mechanisms in the Java language.
- Branching: if-else statement, switch statement
- Loops: while, for, do-while, break can exit the loop, continue can skips the rest statements.
二、Class and Object
Java class:
- Abstract Data Type, define a new data type
- A “generalization” of a real world (or “problem world”) entity
- contains types of data (attributes) & actions (methods)
- represents a template for things that have common properties
- fundamental unit of abstraction in OOP
Object/Instance:
- an instance (concrete example) of a class
- contains state (dynamic information)
- relation between object and class, is a relationship
- created/initialized by new key word
- deceleration of an object will only locate memory, is a null object
Defining a Class:
- Constructor: are methods, used to initialize object, same name as class, provide initial values.
- Getter and Setter: initializing/updating/accessing instance variables of object
- this: a reference to calling object itself
Garbage Collection in Java:
- does not have a valid reference and, therefore, cannot be used in future
- The object becomes a candidate for Java Automatic Garbage Collection
- Java automatically collects garbage periodically, and frees the memory of unused objects
5
Method Overloading:
- same name but different signatures (argument types and/or numbers).
- is a form (core feature) of polymorphism
Static Attribute:
- share among all objects of the class, not specific to any object, one copy per class
- can be modified by both non-static and static methods or using a reference to an object
- can accessed directly from class without creating an instance.
Static Method:
- a method that does not depend on (access or modify) any instance variable
- is invoked (called) using the class name.
- Static methods can only call other static methods.
- Static methods can only access static data.
- cannot refer to Java keywords such as, this or super
- the entry pointer of Java application is a static method
Standard Method:
- are frequently used, that are provided as standard methods in every class
- equals: is used to check object’s logical equality, == check reference equality.
- default implement of equals will check refence equality of two objects.
- toString: returns a String representation of an object, default implement is object reference
- copy constructor: exact, separate, independent, and deep copy of the argument object
Visibility Modifiers (with information hiding):
- public: makes it available/visible everywhere
- private: makes them only visible within that class, are not inherited
- default: makes them only visible within that class, and classes that are in the same package
6
Mutability:
- Mutable Class: contain public way that can change the instance variables
- Immutable Class: no public way to change instance value, object called immutable object.
Wrapper Class:
- A class that gives extra functionality to primitives like int, and lets them behave like objects
- Allows primitive data types to be “packaged” or “boxed” into objects
- Allows primitives to “pretend” that they are classes
- Provides extra functionality for primitives
- primitive to wrapper: Boxing
- wrapper to primitive: Unboxing
Parsing:
- Processing one data type into another
三、Object-Oriented Design paradiam:
Data Abstraction:
- the technique of creating new data types (Class) that are well suited to an application
Encapsulation:
- The ability to group data (attributes) and methods that manipulate the data to a single entity.
- Unique to OOP, not provided by procedural programming.
- A class encapsulates data and the methods that operate on the data into a single unit.
Information Hiding:
- Ability to “hide” the details of a class from the outside world
- Information Hiding is also referred to as Visibility (Access) Control
- Preventing an outside class from manipulating the properties of another class in undesired ways.
- prevents programmers from relying on details of class implementation
7
- protects against accidental or wrong usage
- keeps code elegant and clean (easier to maintain)
- provide access to the object through a clean interface
Delegation:
- A class can delegate its responsibilities to other classes
- An object can invoke methods in other objects through containership
- this is an Association (has a) relationship between the classes
- extend functionally, promotes code reuse
Polymorphism:
- same method – different behavior
- include method overriding, method overloading, generic, inheritance, interface
四、Java Package:
Java Package:
- Allows to group classes and interfaces (will be introduced later) into bundles
- It is another level of Encapsulation
- allows code reuse
- prevents naming conflicts
- allows access control
- import statement: to use package
Default Package:
- no package statement is needed, automatically available to a program.
- all the classes in the current directory belong to an unnamed default package
8
五、Arrays and Strings:
Arrays:
- A sequence of elements of the same type arranged in order in memory
- is a derived Data Type
- declaring an array does not define an array
- arrays must be initialized with size
- Arrays are references, manipulating one reference affects all references
- Arrays can be used to store objects
Multi-Dimensional Arrays:
- Technically exist as “array of arrays”
- Declared just like 1D arrays
Arrays Methods:
- Indexing: can get element by index
- Length: array.length()
- Equality: Arrays.equals(array1, array2)
- Resizing: creating a new array
- Sorting (ascending): Arrays.sort(array1)
- Printing: Arrays.toString(array1), will call all toString method for every object in array1
- Loop: for ( varName : ) {}
Limitations of array:
- finite length
- resizing is a manual operation
- requires effort to “add” or “remove” elements
9
String:
- A Immutable Java class made up of a sequence of characters.
- String method will create a new String; the origin object will not change.
- powerful for input and output
- can’t be modified, only replaced
- every String operation returns a new String
String Method:
- Length: string.length()
- Upper/Lower Case: string.toUpperCase()
- Split: string.split(“ ”)
- contains: string.constains()
- find location: string.indexOf()
- sub string: string.substring()
- equal (always use equal to check equality): string.equals()
六、Input and Output:
Input:
- Command line arguments
- User input
- Files
Output:
- Standard output (terminal)
- Files
Command Line Argument:
- information or data provided to a program when it is executed
- accessible through the args variable
10
public static void main(String[] args):
- args is a variable that stores command line arguments
- String[] means that args is an array of String
For multiword Strings, use quotes:
- Command Line Argument: Hello World 10 → in args: (“Hello”, “World”, “10”)
- Command Line Argument: “Hello World” 10 → in args: (“Hello World”, “10”)
Scanner:
- import java.util.Scanner
- Scanner scanner = new Scanner (System.in)
System.in:
- an object representing the standard input stream, or the command line/terminal
- reference to the input stream, not the Computer System
scanner.nextLine():
- reads a single line of text (including blank space), up until a “return” or newline character
- only method that can eat the newline character
scanner.next():
- reads words (String) separated by space
- scanner.nextDouble(), scanner.nextFloat(), scanner.nextInt() only match expected data types
scanner.hasNext():
- returns true if there is any input to be read
scanner.hasNextXXX():
- returns true if the next “token” matches XXX
11
FileReader:
- a low level file for simple character reading
BufferedReader:
- a higher level file that permits reading Strings, not just characters
FileWriter:
- a low level file for simple character output, used to create
PrintWriter:
- a higher level file that allows more sophisticated formatting (same methods as System.out)
Try-Catch Block:
- try: automatically close the file once we’re done
- catch: acts as a safeguard to potential errors
- finally: perform clean up (like closing files) assuming the code didn’t exit
七、Inheritance and Polymorphism:
Inheritance:
- a form of abstraction
-“Is A” a elationship
- permits “generalization” of similar attributes/methods of classes;
- analogous to passing genetics to your children
- promotes code reuse
Superclass:
- the “parent” or “base” class in the inheritance relationship;
- provides general information to its “child” classes.
- methods of the superclass cannot access public attributes of a subclass (time-orderproblem)
- methods in the parentclass that are only used by subclasses should be defined by protected
12
Subclass:
- the “child” or “derived” class in the inheritance relationship;
- inherits common attributes and methods from the “parent” class
- automatically contains all (public/protected) instance variables and methods in the base class
- “more specific” versions of a superclass
- subclasses cannot call private methods, and cannot access private attributes of parent classes
- subclasses can call public/protected methods, and can access public/protected attributes of
parent classes
- subclasses can only increase the visibility, cannot decrease the visibility
- public method in the parent class must remain public in the child class
- protected method can remain protected or made public extends:
- indicates one class inherits from another
- cannot extends each other super:
- a reference to an object’s parent class;
- just like this is a reference to itself, super refers to the attributes and methods of the parent
super(signatures):
- invokes a constructor in the parent class
- must be at the top of the code section
- can have multiple constructors (method overloading)
Method Overriding:
- same signature, declaring a method that exists in a superclass again in a subclass
- can only be overridden by subclasses
- static & private methods do not have Overriding
- overriding cannot change return type (except when changing to a subclass of the original)
13
Consistent Rules in Inheritance:
- child objects can be assigned to a reference of itself OR a reference of parent objects
- parent objects cannot be assigned to a reference of child objects
- when a method is defined only in the parent class, it gets called regardless of the object type
- method with the same signature, it will be executed purely depends on the type of object
- only define common variables in the superclass
Shadowing (Don’t Do It):
- when two or more variables are declared with the same name in overlapping scope
- the variable accessed will depend on the reference type rather than the object.
final:
- indicates that an attribute, method, or class can only be assigned, declared or defined once.
- used when you do not want subclasses to override a method (still can use the method)
Privacy Leaks:
- define attributes as protected may result in privacy leaks
- attributes should be accessed via public or protected methods in the parent class
Every class in Java implicitly inherits from the Object class :
- All classes are of type Object
- All classes have a toString, equals method
- we can override them
equals:
- public boolean equals(Object otherObject)
- Object is everyone’s parent
14
get
Class:
- returns an object of type class that represents the details of the calling object’s class
instanceof:
- an operator that gives true if an object A is an instance of the same class as object B
- OR a class that inherits from B (e.g. return new Rook() instanceof Piece → true)
Upcasting:
- when an object of a child class is assigned to a variable of an ancestor class
- E.g. Piece p = new Rook(2, 3) ;
Downcasting:
- when an object of an ancestor class is assigned to a variable of a child class.
- only makes sense if the underlying object is actually of that class (have to think carefully)
- E.g. Piece robot = new WingedRobot(); WingedRobot plane = (WingedRobot) robot;
abstract:
- defines a Class that is incomplete
- abstract classes are “general concepts”, rather than being fully realized/detailed
- defines a superclass method that is common to all subclasses, but has no implementation.
- each subclass then provides its own implementation through overriding.
- E.g. public abstract boolean isValidMove (int toRow, int toColumn); (has no brackets)
Abstract Class:
- a class that represents common attributes and methods of its subclasses,
- but that is missing some information specific to its subclasses.
- may have abstract methods, can have no abstract methods
- classes with abstract methods must be abstract
15
- cannot be instantiated
- represent an incomplete concept, rather than a thing that is part of a problem
Concrete Class:
- any class that is not abstract,
- has well-defined, specific implementations for all actions it can take.
Types of Inheritance:
- Single inheritance (only one super class)
- Hierarchical inheritance (one super class, may sub classes)
- Multi-Level inheritance (derived from a derived class)
八、Interface and Polymorphism:
Interface:
- declares a set of constants and/or methods that define the behavior of an object.
-“Can do” relationship
- classes that implement interface can do all the actions defined by the interface
- interfaces cannot have instance variables
- interfaces cannot be instantiated
- generally called <...>able (e.g., public interface Printable {...})
- methods never have any code
- all methods are implied to be abstract
- all attributes are implied to be static final (not necessarily write static final)
- all methods and attributes are implied to be public (not necessarily write public)
- e.g. int MAXIMUM_PIXEL_DENSITY = 1000; void print();
- can be extended just like classes, used to addadditional, specific behavior
- Interface can extend multiple interfaces, but can only extend one class
16
Implements:
- declares that a class implements all the functionality expected by an interface
- concrete classes that implement an interface must implement all methods it defines
- classes that don’t implement all methods must be abstract
default:
- indicates a standard implementation of a method,
- that can be overridden if the behavior doesn’t match what is expected of the implementing
Sorting:
- Arranging things in an order
- Arrays.sort(arrayOfThings);
- String Class implements Comparable, can therefore be sorted automatically
compareTo():
- defines a method allowing us to order objects
- compares exactly two objects, A and B
- B can be a subclass of A, since they are both Comparable
- returns a negative integer (less than), zero (equal to), or a positive integer (greater than)
Interface vs Inheritance:
Inheritance:
- generalizing shared properties between similar classes;
- “Is a” relationship, contains hierarchical relationship
- E.g. All Dogs are Animals
- Classes can only inherit one class
17
Interface:
- generalizing shared behavior between (potentially) dissimilar classes;
- “Can do” relationship, a Comparable object can be compared when sorting
- E.g. Strings can be compared and sorted
- E.g.There is no logical relationship between Clothing and Seatbelt, they can both be“worn”
- Classes can implement multiple interfaces
九、Modelling Classes and Relationships:
Design Algorithm:
- identify classes: noun extraction
- identify class relationships: identify has-a, is-a, can-do type of relationships
- refine classes and relationships
- develop a class diagram: combine classes and relationships
- represent using an accepted notation: UML is a widely accepted industry standard
Unified Modeling Language (UML):
- a graphical modelling language that can be used to represent object-oriented analysis,
- include design and implementation.
- UML is only one notation/tool
- What we draw is class diagram
Components of an attribute:
- name (e.g. xPos)
- data type (e.g. int)
- initial value (e.g. = 0) → privacy (e.g. +)
- static (e.g. numMethodCalls: int)
18
multiplicity:
- finite: [10] (array)
- range (known) [1..10] (array or list, etc.) → range (unknown) [1..*] (list, etc.)
- range (Zero or More) [*] (list, etc.)
Representing access control:
- + public
- ~ package
- # protected
- private
Components of a method:
- name (e.g. render())
- privacy (e.g. +)
- return type (e.g. : void)
- parameters (e.g. name: String)
Representing Class Relationships:
- Association: A link indicating one class contains an attribute that is itself a class.
- Association: Does not mean one class “uses” another (in a method, or otherwise)
- Aggregation: different form of association, independent ‘has’ relationship
- Composition: different form of association, one class cannot exist without the other
Multiplicity:
- specifies the number of links that can exist between instances (objects) of the classes
19
Generalization (Inheritance):
- Abstract Classes: italicized methods or classes are abstract
Realization (Interfaces):
- use dotted line / dashed line to represent Dependency:
- represents a weak relationship between classes
- implies that a change to one class may impact the other class → represented by a dotted arrow
十、Generic:
Generic Class:
- A class that is defined with an arbitrary type for a field, parameter or return type.
- type parameter is included in angular brackets after the class name in the class heading.
- a type parameter can have any reference type (i.e., any class type)
- a single uppercase letter is used for a type parameter, but not forced
- a class definition with a type parameter is stored in a file and compiled just like any other
- enables generic logic to be written that applies to any class type
- allows code re-use
Type Parameters:
- T is a type parameter, or type variable
- the value of T is literally a type (class/interface): Integer, String, Robot, Book, Drivable...
- when T is given a value (type), every instance of the placeholder variable is replaced
- allow us to define a class or method that uses arbitrary, generic types, that applies to any types
- make the solution more elegant
ArrayList Class:
- a generic class with an array as an instance variable, solves the above problems
- can be iterated like arrays (for-each)
- automatically handles resizing
20
- can insert, remove, get, and modify elements at any index (plus many more capabilities)
- inherently able to toString()
- can be easily sorted if the stored element class implements the Comparable interface,
- the compareTo() method of the class must provide a comparison (returning an integer)
- Collections.sort() could automatically sort (should implement Comparable )
Limitations of the ArrayList Class:
- although an ArrayList grows automatically when needed, it does not shrink automatically,
- trimToSize() method can be invoked to release the excess memory
- cannot store primitive data types (int, float, etc.)
Generic Methods:
- A method that accepts arguments, or returns objects, of an arbitrary type
- can be defined in any class
- the type parameter is local to the method
Limitations of Generic Programming:
- cannot instantiate parametrized objects
- cannot create arrays of parametrized objects
十一、Collections and Maps:
Collections:
- A framework that permits storing, accessing and manipulating lists
- with order
Maps:
- A framework that permits storing, accessing and manipulating key-value pairs.
- with no order
21
Anonymous Inner Class:
- A class created “on the fly”, without a new file,
- use for a class for only a single object is created
Collections Operations:
- Length: int size()
- Presence: boolean contains(Object element) [only works with equals() method]
- Add: boolean add(E element)
- Remove: boolean remove(Object element)
- Iterating: Iterator iterator()
- Iterating for (T t: Collection)
- Retrieval Object get(int index) [Supported only at AbstractList level and below]
Maps Operation s:
- Length: int size()
- Presence: boolean containKey(Object key)
- Presence: boolean containValue(Object value)
- Add/Replace: boolean put(K key, V value)
- Remove: boolean remove(Object key)
- Iterating Set keySet()
- Iterating Set> entrySet() → Retrival V get(Object key)
Generics in the Collections and Maps:
- give us flexibility
- code once, reuse the code for any type
- allow objects to keep their type (i.e. not the Objects)
- allows the compiler to detect errors, prevent run-time errors if code is properly designed
22
十二、Design Patterns:
Design Patterns:
- a description of a solution to a recurring problem in software design
- systematically document re-occurring design solutions so that they can be reused
- the recurring nature of the problems makes the solution useful to software developers
- in the form of a Pattern enables the solution to be used without reinventing the wheel
Singleton Pattern:
- ensure that a class has only one instance and provide a global point of access to it
- is a creational pattern
- there are cases where only one instance of a class must be enforced and provide access
- has a private constructor
- invoke using Singleton.getInstance()
Template Method pattern:
- uses Inheritance
- classes implementing same algorithms, only small details are different
- generic algorithm is placed in the base class
- specific implementation is deferred to the sub class
- the design tradeoff of using inheritance is the strong dependency to the base class
Strategy pattern:
- uses Delegation
- Delegate core functionality to other classes, implement the details in it (or its sub class)
Factory Method Pattern:
- defining a separate operation for creating an object
- creating an object by calling a factory method
- factory: A general technique for manufacturing (creating) objects
23
- product: An abstract class that generalizes the objects being created/produced by the factory
- creator: An abstract class that generalize the objects that will consume/produce products,
- creator generally have some (constuctor) that will invoke the factory method
- loose coupling between client code and object creations.
- object creation is now all centralized to the factory
Observer Pattern:
- decouples the subject and observers using a publish-subscribe style communication pattern
- subject: An ‘important’ object, whose state (change) determines the actions of other classes
- observer: An object that monitors the subject in order to respond to its state (change),
- subject will automatically notifies observers of state changes
- with some extra tools, powers a great deal of event-driven programs
- clear responsibilities: subjects know nothing about the observers, except that they exist
- observers can be added or removed from subjects at will, with zero effect
- can be extended in various ways to improve messaging, decoupling, and event-handling
Creational Patterns:
- solutions related to object creation
- E.g. Singleton, Factory Method
Structural Patterns:
- solutions dealing with the structure of classes and their relationships
- E.g. Adapter, Bridge
Behavioral Patterns:
- solutions dealing with the interaction among classes
- E.g. Strategy, Template Method, Observer
24
十三、Exception:
Syntax Error:
- Errors where what you write is not legal code; identified by the editor/compiler
Semantic Error:
- Code runs to completion, but results in incorrect output/operation; (software testing)
Runtime Error:
- An error that causes your program to end prematurely, identified through execution
Common Runtime Errors:
- dividing a number by zero
- accessing an element that is out of bounds of an array
- trying to store incompatible data elements
- using negative value as array size
- trying to convert from string data to another type
- file errors: operating a file in “read mode” that does not exist or no read permission
Exception:
- An error state created by a runtime error in your code, in an exception:
- An object created by Java to represent the error that was encountered
Exception Handling:
- Code that actively protects your program in the case of exceptions
Chaining Exceptions:
- chain catch blocks to deal with different exceptions separately.
- the most “specific” exception (subclass) come first, exceptions (super classes) listed below
25
throw:
- respond to an error state by creating an exception object,
- either already existing or one defined by you
throws:
- indicates a method has the potential to create an exception,
- cannot be bothered to deal with it (Slick stupidly does this for everything),
- or that the exact response varies by application
Exceptions are classes:
- most exceptions inherit from an Exception class
- all exceptions should have two constructors, but we can add whatever else we like
Unchecked:
- exceptions that are not checked at compile time.
- the compiler will not give an error if an unchecked exception is not handled
- NullPointerException, ArrayIndexOutOfBound, etc
Checked:
- exceptions that are checked at compile time by the compiler.
- inherit from the Exception class and are not subclasses of RuntimeException
- IOException, SQLException, ClassNotFoundException, etc
- checked Exceptions must be either handled or declared in the calling method
Using Exceptions:
- should be reserved for when a method encounters an unusual
- or unexpected case that cannot be handled easily in some other way
26
十四、Software Testing and Design:
Code Formatting:
- use consistent layout (indentation, white space)
- avoid long lines (80 characters is ‘historic’)
- beware of tabs
- lay out comments and code neatly
- sensible naming of variables, method and classes
- divide long files into sections with clear purposes
- avoid copy and pasting/duplicating code
- use a comment to explain each section
Comment Style:
- intended primarily for yourself, and developers writing code with you
- code should be written to be self-documenting; readable without extra documentation
- comments “tell the story” of the code
- if your code were removed, comments should be sufficient to “piece together” the algorithm
- comments should be attached to blocks of code, correspond to steps your algorithm
Javadoc:
- a special kind of comment that can be compiled to HTML
- intended primarily for developers using your program (exactly like Slick documentation)
- used to document packages, classes, methods, and attributes (among others)
- should document how to use and interact with your classes and their methods
- various @tags (like @param and @return) for generating specific documentation
GRASP:
- General Responsibility Assignment Software Patterns/Principles
- a series of guidelines for assigning responsibility to classes in an object-oriented design
- how to break a problem down into modules with clear purpose
27
Cohesion:
- classes are designed to solve clear, focused problems.
- the class’ methods/attributes are related to, and work towards, this objective.
- designs should have maximum cohesion.
Coupling:
- the degree of interaction between classes;
- dependency between classes.
- designs should have minimum (low) coupling
Open-Closed Principle:
- classes should be open to extension, but closed to modification
- in practice, this means if we need to change or add functionality to a class,
- we should not modify the original, but instead use inheritance
Abstraction:
- solving problems by creating abstract data types to represent problem components
- achieved in OOP through classes, which represent data and actions Encapsulation:
- the details of a class should be kept hidden or private,
- and the user’s ability to access the hidden details is restricted or controlled.
- also known as data or information hiding
Unit:
- a small, well-defined component of a software system with one,
- or a small number, of responsibilities.
Unit Test:
- verifying the operation of a unit by testing a single use case (input/output),
- intending for it to fail
28
Unit Testing:
- identifying bugs in software by subjecting every unit to a suite of tests
Manual Testing:
- testing code manually, in an ad-hoc manner.
- generally difficult to reach all edge cases, and not scalable for large projects
Automated Testing:
- testing code with automated, purpose-built software.
- generally faster, more reliable, and less reliant on humans assert
- A true or false statement that indicates the success or failure of a test case
TestCase class:
- a class dedicated to testing a single unit
TestRunner class:
- a class dedicated to executing the tests on a unit
Advantages of Junit:
- easy to set up
- scalable
- repeatable
- not human intensive
- incredibly powerful
- finds bugs
Software Tester:
- conducts tests on software, primarily to find and eliminate bugs
29
Software Quality Assurance:
- actively works to improve the development process/lifecycle.
- directs software testers to conduct tests, primarily to prevent bugs
十五、Even Driven Programming:
Sequential Programming/Synchronous Programming:
- A program that is run (more or less) top to bottom,
- start at the beginning of the main method, and concluding at its end
- useful for “static” programs
- constant, unchangeable logic
- execution is the same (or very similar) each time
Event Driven Programming Key Word:
- State: the properties that define an object or device; for example, whether it is “active”
- Event: created when the state of an object/device/etc. is altered
- Callback/ Listener: a method triggered by an event
Event-Driven Programming:
- using events and callbacks to control the flow of a program’s execution.
- E.g., exception handling: exception is an ‘event’, do something accordingly is ‘callback’
- E.g., observer pattern
- better encapsulate classes by hiding their behavior
- avoid having to explicitly send information about the input;
- instead it is automatically passed as part of the callback
- easily add/remove behavior to classes
- easily add/remove additional responses
30
Event Handler:
- objects are created that can fire events
- listener objects are created that can react to the events
- next thing that happens depends on the next event
- methods are invoked automatically when an event signals that the method needs to be called
Software Development Frameworks:
- An Object-oriented framework is a set of cooperating classes that represent reusable designs
- normally consists of a set of abstract classes (that are partially complete) and interfaces
- partially complete classes can be customized to meet application needs
Software Development Frameworks – Key Feature:
- Extensibility: Consists of a set of abstract classes and interfaces to be extended or specialized
- Extensibility: The changeable aspects are represented as hook methods
- Inversion of Control: with conventional library, application acts as the master
- Inversion of Control: With application development framework, framework acts as the master
- Design Patterns as building blocks: use design patterns as building blocks
十六、Advanced Java:
enum:
- a class that consists of a finite list of constants
- used any time we need to represent a fixed set of values → must list all values
- they can have methods and attributes
- sort by the sequence defined by the Enum Class
Variadic Method:
- a method that takes an unknown number of arguments
- implicitly convert the input augments into an array
31
Functional Interface:
- an interface that contains only a single abstract method
- also called a Single Abstract Method interface
- can contain only one ‘new’ non-static method, adding more will raise an error
Predicate functional interface:
- public interface Predicate
- represents a predicate, a function that accepts one argument, and returns true or false →
- executes the boolean test(T t) method on a single object
- can be combined with other predicates using the and, or, and negate methods
UnaryOperator functional interface:
- represents a unary (single argument) function that accepts one argument,
- returns an object of the same type
- executes the T apply(T t) method on a single object
Lambda Expression:
- a technique that treats code as data that can be used as an ‘object’;
- for example, allows us to instantiate an interface without implementing it.
- takes zero or more arguments (source variables) and applies an operation to them
- can often be used in place of anonymous classes, but are not the same thing
- are instances of functional interfaces
- allow us to treat the functionality of the interface as an object
- makes our code much neater, and easier to read
Method Reference:
- an object that stores a method;
- if that lambda expression is only used to call a single method, it can take place
32
Streams:
- a series of elements given in sequence, are automatically put through a pipeline of operations
- allow you to apply sequential operations to a collection of data
- map (convert input to output)
- filter (select elements with a condition)
- limit (perform a maximum number of iterations)
- collect (gather all elements and output in a list, array, String...)
- reduce (aggregate a stream into a single value)