Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: THEend8_
SWEN20003-OOSD
一、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