Uploaded by Lovely Girl

Java OOP Fundamentals: Introduction & Concepts

advertisement
ICT1009 Object-Oriented Programming
Lecture 1: Java introduction & Fundamentals
Dr. Nisha Jain
Acknowledgement: Dr. Peter Loh & Dr.Wang Zhengkui & Dr. Oran
2
Objective
• Understand Object Oriented Programming
concepts
• Learn the Java and C++ basics
• Use Java and C++ for programming
4
Learning Outcomes
• To develop basic object-oriented applications in
Java
• To apply appropriate Java APIs in OO application
development
• To apply appropriate C++ APIs in OO application
development
• To develop basic object-oriented applications in
C++
• To apply basic test-first programming
5
Why OOPs???
14
Why OOPs???
• What if we want to create a software which we can
assemble and reuse
– Pick up small snippets from here and there
– Re use codes
• Procedural Languages (like C) - disadvantages
– A long piece of code combining data and logic all together (re
use difficult)
– Mostly uses functions
– Separates data structure from algorithm
– High level abstraction is tough (real life problems difficult)
15
Why OOPs???
• Object Oriented Programming Language
– Basic unit is a class
Name
– Static members
Attributes
– Dynamic methods
Behavior
– Object -> instance of a class
17
Why Learn Java?
• Open source programming language created by Sun Mc
overtaken by Oracle
• Platform-independent (JVM)
• Comparatively secure and reliable – Byte code
• Compile once and run forever
• Free comprehensive IDEs e.g. Eclipse, Netbeans
18
Before the OO design
• requirements specification: desired implementationindependent functionality of the system as a whole.
• conceptual model: Implementation-independent diagram
• use cases: Descriptions of sequences of events.
• user interface prototype: look and feel of the product’s UI.
• data model: abstract description of how data is represented
and used in the system
20
Core OOPs Concepts
• Abstraction - Classes and Objects
• Encapsulation – Modifier of class attributes and behavior (public,
protected and private )
• Inheritance – Inheriting properties from base class, Interfaces
• Polymorphism – Method overloading and Overriding
21
Basics
• Using simple concepts to represent complex problems
• Class - A template definition of the methods and properties of
one particular kind of object in real world.
• An object is created from the class
– specific instance of a class
– contains real values instead of variables
• One class can create multiple objects
– Multiple instances of the class
Class
Objects
22
Encapsulation
• Protective barrier that prevents the code and data being
randomly accessed by other code defined outside the class
• Hiding the details of how the object works
– The only part of the object that is accessible to the outside
world is its behaviors.
23
Inheritance
• Derive a new class from an
existing one
• Existing class - parent class, or
superclass, or base class
Cycle
• Derived class - child class or
subclass
– Inherits characteristics of the
parent (methods and data)
Plain Bicycle
– Option of overriding any
attribute of the parent class
– Can add new attributes
GearedCycle
24
Polymorphism
• Poly = “many” and morph =
“form”
– Same functions means different
things in different contexts
• Overloading lets you define a
similar operation in different
ways for different data
• Overriding lets you define a
similar operation in different
ways for different object types
Example - Animal class having
Speak function which returns
animal sound for the respective
animal
OOPs and Java
• A class is a template for creating objects
• A class has attributes and methods
• A Java program has classes as building blocks
• A class has a constructor for creating objects
• A Java program contains a method called main
Class
An object is an instance
of a class
Objects
26
Java Language Specification, API, JDK & IDE
• Java syntax is defined in Java language specification
• Java library is defined in the java API
• JDK(Java Development Kit) is the software of developing
and running java programs
• IDE: integrated development environment for
developing java program (Eclipse)
27
How java works?
Step 1
Step 2
Step 3
Step 4
Step 5
28
Creating, compiling and executing a Java program
• Step 2 - Save a program into .java file
• Step 4 - Compile it into .class file
• Step 5 - The .class is executed in the java virtual
machine
29
Java Program Structure – Example 1
class header
method header
•
•
•
•
•
•
•
Comments can be // or /* */ or /** */
System locates and runs the main method
Must be public, static and void
Static methods can be called without instantiating class
Other methods get executed when called by main
Spaces, blank lines, and tabs are called white space
Can be used to format programs – easier to read and maintain
30
Java Program Structure – Example 2
 System.out represents the console in Eclipse
 print does not advance to new line, println does
 String concatenation operator (+) joins strings and numbers
31
Escape Sequences
What if we wanted to print a “ character?
 The following line would confuse the compiler:
System.out.println("I said "Hello" to you.");
32
32
Escape Sequences
An escape sequence begins with a backslash (\)
System.out.println ("I said \"Hello\" to you.");
33
Java Data Types
Data
Type
boolean
char
byte
short
int
long
float
double
Default
Value
false
‘\u0000’
0
0
0
0L
0.0f
0.0d
Default
Size
1 bit
2 bytes
1 byte
2 bytes
4 bytes
8 bytes
4 bytes
8 bytes
34
Variables in Java
• Associated with a memory location
• Must be declared by giving it a name and type of data that it will
hold
data type
variable name
int age;
• Made up of letters, digits, the underscore character ( _ ), and the
dollar sign ($)
• Can’t begin with a digit and is case-sensitive
• By convention, we use:
– title case for class names - Lincoln
– upper case for constants - MAXIMUM
35
Constants and Assignment
 A constant holds the same value throughout execution
 The compiler will issue an error if you try to change the value of a
constant
 Use the final(static) modifier to declare a constant:
final static int MIN_HEIGHT = 69
 Give meaning to otherwise unclear literal values – facilitate
maintenance (edit once, use many places)
 Variables must be assigned values of consistent type:
int num = 73
36
Casting and Data Type Conversions
• Converting object of one type into another type
• No direct casting from char to String
• No automatic conversion from or to the type boolean
• There may be loss of accuracy / precision
Casting and Auto Conversion Examples
•
int i = (int) 1.345;
•
byte y = (byte)i;
•
long l = i;
•
float f = l;
•
String greet = “Hello World”;
•
Object g = (Object)greet;
37
Conditional Construct
• Selection Construct
▪
The if – else if works in a similar way as in C, Python
• Switch Construct
▪ Each case is tagged with
a value and list of
statements
▪ The default case is
selected when variable
≠ c1, c2, c3, c4
▪ What happens if break
is removed (test with
Example 4)?
38
Switch-case
Switch-case
39
Repetition Constructs
• statement(s) executed as long as
expression evaluates to true
• statement(s) executed as long as
expression evaluates to true
(Example 5)
• statement(s) executed as long as
termination evaluates to false
(Example 6)
40
do-while
41
for loop
42
Java Imports and Packages
• Header files == Packages
• Useful built in classes and methods
• Instead of include use “import”
– Eg. import java.util.*; it brings in all classes from util package in
your source file
• Create your own package
– Allows classes to be grouped together under one umbrella
– At most one package declaration can appear in a source file with
keyword “package”.
• Eg. package whattodo;
43
New Keyword
• Used to create an object of a class
• Allocates memory at runtime
public class NewExample{
void display()
{
System.out.println("Hello!");
}
public static void main(String args[]){
NewExample egs = new NewExample();
}
}
44
Input and Output Streams
• Program input and output are handled by streams
• System.out.print, System.out.println
• Scanner userTry = new Scanner(System.in)
45
Console Input
• Scanner class object
– Need to import java.util.scanner
Scanner userTry = new Scanner(System.in);//reads from System.in
String nextStatement = userTry.next();//get next input token
char p_move = nextStatement.next().charAt(0);//reads first character of the
input
• A BufferedReader object performs buffered input.
– A buffer is memory where data is held until needed by the program.
– Need to import java.io.* – all IO classes except Scanner
46
Console Input
new – instantiates Scanner
• The Scanner utility provides a way to do console input
• next().charAt(0) returns character value at index 0
47
Console Input
 Reads text from a character input stream
 Buffers characters for efficient reading of characters, arrays, and lines
 Advisable to use BufferedReader for FileReaders and InputStreamReaders whose read()
operations may be costly
 parseInt converts String input to integer (input string value must be whole number else
exception)
 parseDouble converts String input to double (input string value can be whole number or
float)
48
 parseInt(String, base) treats input string whole number as a value in base
File Input and Output
• A File object is either a file or folder
• How do we create a folder and do file IO?
49
Array Data Types
•
•
•
•
Index starts at 0
Initialized arrays can’t shrink or grow
Bounds checking (no overflow!) – ArrayIndexOutOfBoundsException
Arrays have a .length
Array Definition Examples
int[] values;
int[] foo = {1,2,3,4,5};
String[] names = {“Joe”, “Sam”};
int x[] = new int[1000];
byte[] buff = new byte[256];
float[][] mvals = new float[10][10];
52
Multi-Dimensional Array Data Types
Array Definition Examples
int a[][];
a = new int[
b = new int[
b[ 0 ] = new
b[ 1 ] = new
3 ][
2 ][
int[
int[
4 ];
];
// allocate rows
5 ]; // allocate columns for row 0
3 ]; // allocate columns for row 1
53
Collection data types in Java
•
•
•
•
•
ArrayLists
Linked Lists
Stacks
Queues
Trees
54
ArrayList Example
•
•
<String> is a type parameter - we will talk about this later
What are the other methods of an ArrayList?
57
LinkedList Example – Word Counter
•
Explain how this program works and why use .equals instead of
== ?
58
Summary
• Introduction to Java
• Java Building Blocks
•
•
•
•
•
Basic building blocks
Conditional statment
Input/Output – Streams, Consoles and Buffers
File methods – create, read, write, and close
Collection data types – ArrayList, LinkedList, Stack
and Queue (support storage of variable-sized
dataset
59
60
Download