1 java language java basics. 2 java is familiar, simple & small java is familiar because it...

56
1 Java Language Java Basics

Upload: albert-prosper-boone

Post on 11-Jan-2016

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

1

Java LanguageJava Language

Java BasicsJava Basics

Page 2: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

2

Java is Familiar, Simple & SmallJava is Familiar, Simple & Small Java is Java is familiarfamiliar because it looks like C/C++. Having because it looks like C/C++. Having

Java retain the “look and feel” of C/C++ enables Java retain the “look and feel” of C/C++ enables programmers to migrate easily.programmers to migrate easily.

Java is Java is simplesimple and and smallsmall (there are only 49 keywords (there are only 49 keywords in Java). This is because Java removes many of the in Java). This is because Java removes many of the complex, redundant, dubious and error-prone complex, redundant, dubious and error-prone features of C/C++, such as pointer, multiple features of C/C++, such as pointer, multiple inheritance, operator overloading, memory inheritance, operator overloading, memory management (management (mallocmalloc, , freefree), preprocessor (), preprocessor (#define#define, , typedeftypedef, header files), , header files), structstruct, , unionunion, , enumenum, , gotogoto, , automatic coercions, and etc.automatic coercions, and etc.The number of language constructs you need to The number of language constructs you need to understand to get your job done in Java is minimal.understand to get your job done in Java is minimal.

Page 3: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

3

A First Program in JavaA First Program in Java

1 // Fig. 2.1: Welcome1.java1 // Fig. 2.1: Welcome1.java

2 // Text-printing program.2 // Text-printing program.

3 3

4 public class Welcome1 { 4 public class Welcome1 {

5 5

6 // main method begins execution of Java application6 // main method begins execution of Java application

7 public static void main( String args[] )7 public static void main( String args[] )

8 {8 {

9 System.out.println( "Welcome to Java Programming!" );9 System.out.println( "Welcome to Java Programming!" );

10 10

11 } // end method main11 } // end method main

12 12

13 } // end class Welcome113 } // end class Welcome1

Page 4: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

4

Compile and executeCompile and execute

Page 5: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

5

StatementsStatements A A singlesingle statement ends with a semi-colon statement ends with a semi-colon ‘;’‘;’, just , just

like C/C++.like C/C++. A A blockblock statement consists of many statements statement consists of many statements

surrounded by a pair of braces surrounded by a pair of braces {statement(s)}{statement(s)} as as in C/C++.in C/C++.

// Declaration statements// Declaration statements intint score; score;booleanboolean validScore; validScore;

// Assignment statements// Assignment statementsscore = 70;score = 70;validScore = validScore = truetrue;;

// Conditional if statement// Conditional if statementifif ((((score < 0score < 0)) || || ((score > 100score > 100)))) {{ validScore = validScore = truetrue;; System.out.printlnSystem.out.println(("valid score""valid score"));;}}

Page 6: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

6

CommentsComments Multi-lineMulti-line comments: begin with comments: begin with /*/* and end with and end with */*/

(like C/C++). Eg:(like C/C++). Eg:

/* I learn Java/* I learn Java because I’ve been told thatbecause I’ve been told that Java is Kool!Java is Kool!*/*/

Single-lineSingle-line comments: begin with comments: begin with //// and end at the and end at the end-of-line (like C++).end-of-line (like C++).

intint len = 5; len = 5; // Declare, init len to 5// Declare, init len to 5len = 10;len = 10; // Set len to 10// Set len to 10

Page 7: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

7

Variables (or Fields)Variables (or Fields) Variables are “typed” and must be declared with a Variables are “typed” and must be declared with a

typetype and a and a namename (like C/C++) as follows: (like C/C++) as follows:TypeType NameName;;StringString myName;myName; // "Tan Ah Teck"// "Tan Ah Teck"intint myAge;myAge; // 18// 18doubledouble myWeight;myWeight; // 103.33// 103.33booleanboolean isMarried;isMarried; // false or true// false or true

Java is Java is case sensitivecase sensitive!!!!!!!!!!!! A A roserose is NOT a is NOT a RoseRose and is NOT a and is NOT a ROSEROSE

Variable Naming ConventionVariable Naming Convention: nouns, made-up of : nouns, made-up of several words. First word is in lowercase and the several words. First word is in lowercase and the rests are initial capitalized. Eg. rests are initial capitalized. Eg. thisIsALongVariableNamethisIsALongVariableName..

The type can either be a build-in The type can either be a build-in primitiveprimitive type (eg. type (eg. intint, , doubledouble) or an object ) or an object classclass (eg. (eg. StringString, , CircleCircle).).

Page 8: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

8

Primitive Data TypesPrimitive Data TypesTypeType MeaningMeaningbytebyte

IntegerInteger

8-bit signed integer8-bit signed integershortshort 16-bit signed integer16-bit signed integerintint 32-bit signed integer32-bit signed integerlonglong 64-bit signed integer64-bit signed integerfloatfloat Floating pointFloating point

(IEEE 754 (IEEE 754 spec)spec)

32-bit single precision32-bit single precision

doubledouble 64-bit double precision64-bit double precision

charchar16/32-bit “Unicode” character for 16/32-bit “Unicode” character for “Internationalization”“Internationalization”(Unlike C/C++, which uses 8-bit ASCII code)(Unlike C/C++, which uses 8-bit ASCII code)

booleanboolean Logical of either “Logical of either “truetrue” or “” or “falsefalse””(In C/C++, integer 0 for false, non-zero for true)(In C/C++, integer 0 for false, non-zero for true)

nullnull null pointer, no storage allocated.null pointer, no storage allocated.voidvoid Return type for methods: returns nothingReturn type for methods: returns nothing

Page 9: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

9

Assignment, Increment/DecrementAssignment, Increment/Decrement Examples:Examples:

i = 4;i = 4;x = y = z = 0;x = y = z = 0;x += y;x += y; // same as x = x + y; // same as x = x + y;x *= y;x *= y; // same as x = x * y; // same as x = x * y;x++;x++; // same as x = x + 1; // same as x = x + 1;--x;--x; // same as x = x - 1; // same as x = x - 1;

What is the difference between:What is the difference between:y = x++;y = x++;y = ++x;y = ++x;

Page 10: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

10

Operators - Arithmetic & Operators - Arithmetic & ComparisonComparison

OperatorOperator MeaningMeaning ExampleExample++ additionaddition 3 + 4 (=7)3 + 4 (=7)

-- subtractionsubtraction 6 - 4 (=2)6 - 4 (=2)

** multiplicationmultiplication 3 * 5 (=15)3 * 5 (=15)

// divisiondivision 9 / 2 (=4)9 / 2 (=4)

%% modulus (reminder)modulus (reminder) 9 % 2 (=1)9 % 2 (=1)

==== equalequal 1==2 (false)1==2 (false)

!=!= not equalnot equal 1!=2 (true)1!=2 (true)

<< less thanless than 1<2 (true)1<2 (true)

>> more thanmore than 1>2 (false)1>2 (false)

<=<= less than or equal toless than or equal to 1<=2 (true)1<=2 (true)

>=>= more than or equal to more than or equal to 1>=2 (false)1>=2 (false)

Page 11: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

11

Operators - ArithmeticOperators - Arithmetic

OperatOperatoror MeaningMeaning ExampleExample

++ additionaddition 3 + 4 (=7)3 + 4 (=7)

-- subtractionsubtraction 6 - 4 (=2)6 - 4 (=2)

** multiplicationmultiplication 3 * 5 (=15)3 * 5 (=15)

// divisiondivision 9 / 2 (=4)9 / 2 (=4)

%%modulus modulus (remainder)(remainder) 9 % 2 (=1)9 % 2 (=1)

Page 12: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

12

ArraysArrays An An array array is a list of elements of the is a list of elements of the samesame type. type. Identified by a pair of square brackets Identified by a pair of square brackets [[ ]].. Must be Must be declareddeclared with a with a typetype and a and a namename.. Storage must be Storage must be allocatedallocated using operator using operator newnew or or

during during initializationinitialization. E.g.,. E.g.,

intint[][] temps; temps; // Declare an int array temps// Declare an int array tempsintint temps temps[][];; // Same as above// Same as abovetemps = temps = newnew intint[[55]];; // Allocate 5 items// Allocate 5 items

// Declare & allocate array in one statement,// Declare & allocate array in one statement,// initialize to default value.// initialize to default value.intint[][] temps = temps = newnew intint[[55]];;

// Declare, allocate & initialize an array// Declare, allocate & initialize an arrayintint[][] temps = temps = {{1, 2, 3, 4, 51, 2, 3, 4, 5}};;

Page 13: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

13

Array (cont.)Array (cont.)

00 11 22 33 nn-1-1

First IndexFirst Index Last IndexLast Index

lengthlength

Index:Index:

nn

arrayNamarrayNamee

Page 14: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

14

Arrays (cont.)Arrays (cont.) Array Array indexindex begins with 0 (like C/C++) and must be begins with 0 (like C/C++) and must be

of type of type intint, e.g.,, e.g.,tempstemps[[44]] = temps = temps[[22]];;

The The lengthlength of array is kept in an associated variable of array is kept in an associated variable called called lengthlength and can be retrieved using dot and can be retrieved using dot ‘‘..’’ operator.operator.

intint[][] temps = new int temps = new int[[55]];; // 5-item array// 5-item arrayint len = temps.length;int len = temps.length; // len = 5// len = 5

(How to find the array length in C?)(How to find the array length in C?) Build-in array bounds check: index out-of-bound Build-in array bounds check: index out-of-bound

triggers an triggers an ArrayIndexOutOfBoundsExceptionArrayIndexOutOfBoundsException at at runtime. (Software Engineering more important runtime. (Software Engineering more important than execution speed!)than execution speed!)

Multidimensional arrays, eg,Multidimensional arrays, eg,intint[][][][] matrix = new int matrix = new int[[1010][][1010]];;

Page 15: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

15

Flow Control - Conditional Flow Control - Conditional ifif: : ifif (booleanExpression) trueCase (booleanExpression) trueCase

ifif ((x < yx < y)) SystemSystem.out.println.out.println(("x < y""x < y"));;

if-elseif-else: : ifif (booleanExp) trueCase (booleanExp) trueCase elseelse falseCase falseCase

ifif ((x ==x == 00) {) { SystemSystem..out.printlnout.println(("x is 0""x is 0"));;

}} elseelse {{ SystemSystem..out.printlnout.println(("x is not zero""x is not zero"));; x =x = 0;0; // set it to zero// set it to zero

}}

Page 16: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

16

Flow Control - Conditional (cont.)Flow Control - Conditional (cont.) switch-caseswitch-case (Selection) (Selection)

switchswitch ((theOperatortheOperator) {) { // type char or int// type char or int casecase(('+''+')):: result = x + y;result = x + y; breakbreak;; casecase(('-''-')):: result = x - y; result = x - y; breakbreak;; defaultdefault:: SystemSystem.out.println.out.println(("unknown operator""unknown operator"));;}}

Page 17: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

17

Flow Control - LoopFlow Control - Loop forfor: : forfor (initialization; test; increment) statements (initialization; test; increment) statements

intint[][] temps = temps = newnew intint[[55]];;forfor ((intint i=0; i<temps.length; i++ i=0; i<temps.length; i++) {) { SystemSystem.out.println.out.println((tempstemps[[ii])]);;}}

whilewhile: : whilewhile (booleanExpression) trueCase (booleanExpression) trueCase

intint[][] temps = temps = newnew intint[[55]];;intint i=0; i=0;whilewhile ((i < temps.lengthi < temps.length) {) { SystemSystem.out.println.out.println((tempstemps[[ii])]);; i++;i++;}}

Page 18: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

18

Flow Control - Loop (cont.)Flow Control - Loop (cont.) do-whiledo-while: : dodo trueCase trueCase whilewhile (booleanExpression) (booleanExpression)

intint[][] temps = temps = newnew intint[[55]];;intint i=0; i=0;dodo {{ SystemSystem.out.println.out.println((tempstemps[[ii])]);; i++;i++;}} whilewhile ((i < temps.lengthi < temps.length));;

What is the difference between What is the difference between whilewhile and and do-whiledo-while??

breakbreak: break and exit the innermost loop.: break and exit the innermost loop. continuecontinue: abort the current iteration and continue : abort the current iteration and continue

to the next iteration of the loop.to the next iteration of the loop.

Page 19: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

19

ClassClass String String StringString is a sequence of 16-bit Unicode characters is a sequence of 16-bit Unicode characters

enclosed with a pair of double quotes (enclosed with a pair of double quotes (" "" ")), eg., eg."Hi, I'm a string!""Hi, I'm a string!" // single quote OK// single quote OK"" "" // an empty string// an empty string

A Java A Java StringString is NOT an array of characters (unlike is NOT an array of characters (unlike C/C++), but an object classC/C++), but an object class.. (Classes and OOP will (Classes and OOP will be covered later).be covered later).

Need to use the escape sign (Need to use the escape sign (\\) for special ) for special characters such as new-line (characters such as new-line (\n\n), tag (), tag (\t\t), double-), double-quote (quote (\"\"), backslash (), backslash (\\\\), carriage-return (), carriage-return (\r\r), ), form-feed (form-feed (\f\f), Unicode character (), Unicode character (\uhhhh\uhhhh), e.g.,), e.g.,

"A \"string\" nested inside a string.""A \"string\" nested inside a string.""Hello, \u4f60\u597d!""Hello, \u4f60\u597d!"

// 4f60H & 597dH are Unicode // 4f60H & 597dH are Unicode Single-quote (Single-quote ('') does not require escape sign.) does not require escape sign.

Page 20: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

20

StringString Concatenation – ‘+’ Concatenation – ‘+’ operatoroperator

You can use operator plus You can use operator plus ‘‘++’’ to to concatenateconcatenate multiple multiple StringStrings together into a longer s together into a longer StringString..

‘‘++’’ is the only is the only overloadedoverloaded operator in Java. operator in Java. Overloading means different actions will be taken Overloading means different actions will be taken depending on the operands given to the depending on the operands given to the ‘‘++’’ operator. operator. For example,For example,•11 ++ 22 is is 33 ( (intint + + intint gives gives intint))•1.01.0 ++ 2.12.1 is is 3.13.1 ( (doubledouble + + doubledouble gives gives doubledouble))•1.11.1 ++ 22 is is 3.13.1 ( (doubledouble + + intint: the : the intint will be promoted to will be promoted to doubledouble, resulted in , resulted in doubledouble + + doubledouble gives gives doubledouble))

•"Hello ""Hello " ++ "world""world" is is "Hello world""Hello world" ( (StringString + + StringString: : concatenate two concatenate two StringStrings and give a s and give a StringString))

•"Hello ""Hello " ++ 55 is is "Hello 5""Hello 5" ( (StringString + + intint: the : the intint will be will be converted to converted to StringString, and the two , and the two StringStrings concatenated)s concatenated)

•"Hello ""Hello " ++ 1.11.1 is is "Hello 1.1""Hello 1.1" ( (StringString + + doubledouble: the : the doubledouble will be converted to will be converted to StringString, and the two , and the two StringStrings s concatenated)concatenated)

Page 21: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

21

StringString Concatenation Example Concatenation Example StringString str1 = str1 = "Java is hot!""Java is hot!";; // String literal in common pool// String literal in common poolStringString str2 = str2 = newnew StringString(("I'm kool!""I'm kool!"));; // new String object in heap// new String object in heapintint len; len;

SystemSystem.out.println.out.println((str1 str1 ++ " and "" and " ++ str2 str2));; // Gives "Java is hot! and I'm kool!"// Gives "Java is hot! and I'm kool!"

len = str1.lengthlen = str1.length()();; // Get the length of str1// Get the length of str1

SystemSystem.out.println.out.println(("Counted ""Counted " + len + len + + " characters."" characters."));; // Gives "Counted 12 characters."// Gives "Counted 12 characters." // int len is converted to String// int len is converted to String // automatically.// automatically.

Page 22: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

22

Class Class StringString - Examine strings - Examine strings Methods to examine Methods to examine StringString (refer to Java API): (refer to Java API):intint length length()();;StringString substring substring((intint startIdx, startIdx, intint endIdx endIdx));;charchar charAt charAt((intint index index));;intint indexOf indexOf((charchar leftMostChar leftMostChar));;intint lastIndexOflastIndexOf((charchar rightMostChar rightMostChar));;booleanboolean endsWith endsWith((StringString rightMostSubstring rightMostSubstring));;

StringString str = str = "Java is cool!""Java is cool!";;str.lengthstr.length()();; // return int 13// return int 13str.charAtstr.charAt((22));; // return char 'v'// return char 'v'str.substringstr.substring((0, 30, 3));; // return "Jav"// return "Jav"str.indexOfstr.indexOf(('a''a'));; // return 1// return 1str.lastIndexOfstr.lastIndexOf(('a''a'));; // return 3// return 3str.endsWithstr.endsWith(("cool!""cool!"));; // return true// return true

Page 23: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

23

Class Class StringString - Conversion - Conversion StringString is a is a classclass in in java.lang.Stringjava.lang.String. Many useful . Many useful

methodsmethods (or functions) provided in class (or functions) provided in class StringString for for manipulating strings (see Java API). (We will discuss manipulating strings (see Java API). (We will discuss classes & methods later in OOP).classes & methods later in OOP).

Converting a Converting a StringString to other primitive types: to other primitive types:intint anInt = anInt = IntegerInteger.parseInt.parseInt((aStraStr));;floatfloat aFolat = aFolat = FloatFloat.parseFloat.parseFloat((aStraStr));;longlong aLong = aLong = LongLong.parseLong.parseLong((aStraStr));;doubledouble aDouble = aDouble = DoubleDouble.parseDouble.parseDouble((aStraStr));;

Converting a primitive type to Converting a primitive type to StringString::StringString str = str = IntegerInteger.toString.toString((anIntanInt));;StringString str = str = LongLong.toString.toString((aLongaLong));;StringString str = str = FloatFloat.toString.toString((aFloataFloat));;StringString str = str = DoubleDouble.toString.toString((aDoubleaDouble));;

Page 24: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

24

Type Casting for PrimitivesType Casting for Primitives Any numeric type (integer and floating point) can be Any numeric type (integer and floating point) can be

castcast (transformed) to anther type, but some (transformed) to anther type, but some precision may be lost. For example:precision may be lost. For example:

doubledouble f = 3.5; f = 3.5;intint i; i;i = i = ((intint)) f; f; // i = 3, cast optional// i = 3, cast optionalf = f = ((doubledouble)) i; i; // f = 3.0, cast required// f = 3.0, cast required

Java prohibits C/C++ style of “automatic type Java prohibits C/C++ style of “automatic type coercions”. Explicit casting is needed if type coercions”. Explicit casting is needed if type conversion would result in a loss of precision, e.g., conversion would result in a loss of precision, e.g., from from intint to to doubledouble..

Page 25: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

25

Exercise 4d: Command-line Exercise 4d: Command-line ArgumentsArguments

You can supply command-line arguments when You can supply command-line arguments when invoking an application. For example,invoking an application. For example,

> java Arithmetic 1234 456 +> java Arithmetic 1234 456 +

In Java, command-line arguments are packed into a In Java, command-line arguments are packed into a StringString array and passed into the array and passed into the main(String[] main(String[] args)args) method, as the sole parameter method, as the sole parameter argsargs..

In the above example, the 3 In the above example, the 3 StringString arguments arguments "1234""1234", , "456""456" and and "+""+" are packed into a are packed into a String[]String[], , where:where:•args.length is 3 args.length is 3 // // Length of the array Length of the array argsargs•args[0] is "1234" args[0] is "1234" // // Item 0 of the arrayItem 0 of the array•args[0].length() is 4 args[0].length() is 4 // // Length of Length of StringString of Item 0 of Item 0•args[1] is "456" args[1] is "456" // // Item 1 of the arrayItem 1 of the array•args[1].length() is 3 args[1].length() is 3 // // Length of Length of StringString of Item 1 of Item 1

Command-line Command-line ArgumentsArguments

Page 26: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

26

Exercise 4e: Inputs From KeyboardExercise 4e: Inputs From Keyboardimport java.io.*;import java.io.*;public class NumberGuess {public class NumberGuess { public static void main(String[] args) public static void main(String[] args) throws IOExceptionthrows IOException { {

int numberIn;int numberIn; String inStr;String inStr;

// Chain the System.in to a Reader and buffered.// Chain the System.in to a Reader and buffered. BufferedReader in = new BufferedReader(BufferedReader in = new BufferedReader( new InputStreamReader(System.in));new InputStreamReader(System.in));

// Read the guess// Read the guess System.out.print("Enter your guess: ");System.out.print("Enter your guess: "); inStr = inStr = in.readLine()in.readLine(); // return input String; // return input String numberIn = numberIn = Integer.parseInt(inStr)Integer.parseInt(inStr);; ......

Page 27: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

27

Java LanguageJava Language

Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP)

Page 28: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

28

Object-oriented Programming Object-oriented Programming (OOP)(OOP)

Objects are Objects are reusablereusable software componentssoftware components that model that model items in the real world, e.g., student, car, rectangle, items in the real world, e.g., student, car, rectangle, computer, purchase order etc.computer, purchase order etc.

OOP Analogy 1: PC = motherboard + CPU + monitor + OOP Analogy 1: PC = motherboard + CPU + monitor + hard disk + ... To assemble a PC, you need not hard disk + ... To assemble a PC, you need not understand each part in depth or how the parts are understand each part in depth or how the parts are manufactured, but merely the interfaces between manufactured, but merely the interfaces between parts. You can build the part by yourself or get it off parts. You can build the part by yourself or get it off the shelve.the shelve.

OOP Analogy 2: LOGO set. OOP Analogy 2: LOGO set. OOP Analogy 3: A car is made up of engine, OOP Analogy 3: A car is made up of engine,

transmission, body etc. Do you have to know the transmission, body etc. Do you have to know the details of the engine to drive the car? details of the engine to drive the car?

Objects are like “software” ICs (Integrated Circuits).Objects are like “software” ICs (Integrated Circuits). Question: How to program a soccer computer game?Question: How to program a soccer computer game?

Page 29: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

29

Why OOP?Why OOP? Modular and reusable software components.Modular and reusable software components.

No need to re-invent the wheel!No need to re-invent the wheel! Enable programmer to think of program element as Enable programmer to think of program element as

real world objects, and model them accordingly.real world objects, and model them accordingly. More productive in software development.More productive in software development. Ease in software maintenance.Ease in software maintenance.

““SOFTWARE ENGINEERINGSOFTWARE ENGINEERING”” OOP is in contrast to “Procedural Programming” (in OOP is in contrast to “Procedural Programming” (in

C, Pascal, Basic), and was adopted in C++, Java, C#.C, Pascal, Basic), and was adopted in C++, Java, C#. Procedural Programming forces the programmers to Procedural Programming forces the programmers to

think in terms of machine's bits and bytes, object-think in terms of machine's bits and bytes, object-oriented programming lets the programmers to think oriented programming lets the programmers to think in the problem space.in the problem space.

Page 30: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

30

Class & InstanceClass & Instance A A classclass is a definition, implementation, template, or is a definition, implementation, template, or

blueprint of “objects of the same kind”.blueprint of “objects of the same kind”. An An instanceinstance is a “concrete realization” of a is a “concrete realization” of a

particular item of a class. An instance of class is particular item of a class. An instance of class is referred to as an referred to as an objectobject..

Example:Example:• classclass: Student: Student• instancesinstances: “Tan Ah Teck”, “Mohammed Ali”, “Raja : “Tan Ah Teck”, “Mohammed Ali”, “Raja Kumar”.Kumar”.

Page 31: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

31

ClassClass A class has 3 components:A class has 3 components:

1.1. NameName (Identity): a unique identifier. (Identity): a unique identifier.2.2. VariablesVariables (state): static properties, attributes, (state): static properties, attributes, state, data. Java API docs call state, data. Java API docs call fieldsfields..

3.3. MethodsMethods (behavior): dynamic behaviors. Also (behavior): dynamic behaviors. Also called function, procedure or operation.called function, procedure or operation.

CircleCircle

radius=1.4radius=1.4

color="red"color="red"

......

getRadius()getRadius()

computeArea()computeArea()

......

NameName

VariablesVariables(or(or FieldsFields))

(or Attributes)(or Attributes)

MethodsMethods(or (or

operations)operations)

StudentStudent

id=1888id=1888

name="Tan Ah Teck"name="Tan Ah Teck"

......

getName()getName()

printGrades()printGrades()

......

Page 32: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

32

EncapsulationEncapsulation A class in a A class in a self-containedself-contained 3-compartment box of 3-compartment box of

name, variables and methods.name, variables and methods. A class A class encapsulatesencapsulates variables (static attributes) variables (static attributes)

and methods (dynamic operations) inside a 3-and methods (dynamic operations) inside a 3-compartment box. The variables and methods are compartment box. The variables and methods are intimately tied together.intimately tied together.

Procedural language like C is made up of functions. Procedural language like C is made up of functions. Data are separated from the functions (in the Data are separated from the functions (in the header files and global variables). Procedural header files and global variables). Procedural language components are hard to reuse in a new language components are hard to reuse in a new application.application.

OOP program is made up of classes, which are self-OOP program is made up of classes, which are self-contained and encapsulate both the data and contained and encapsulate both the data and methods. You can reuse OOP classes in a new methods. You can reuse OOP classes in a new application easily.application easily.

Page 33: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

33

Class Declaration - ExamplesClass Declaration - Examplespublicpublic classclass Circle Circle {{ // class name// class name privateprivate doubledouble radius; radius; // variables// variables privateprivate StringString color; color;

publicpublic doubledouble computeArea computeArea() {() {......}} //methods//methods publicpublic doubledouble getRadius getRadius() {() {......}} }}

publicpublic classclass Student Student { { // class name// class name privateprivate intint id; id; // variables// variables privateprivate StringString name; name;

publicpublic StringString getName getName() {() {......}} // methods// methods publicpublic voidvoid printGrades printGrades() {() {......}}}}

Page 34: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

34

Class Naming ConventionClass Naming Convention Class Naming ConventionClass Naming Convention: nouns, in mixed case : nouns, in mixed case

with the first letter of each internal word capitalized, with the first letter of each internal word capitalized, e.g., e.g., RasterImageRasterImage, , PrintStreamPrintStream..

Page 35: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

35

Creating Instances of a ClassCreating Instances of a Class To create an instance of a class:To create an instance of a class:

1. 1. DeclareDeclare a name of the instance, belonging to a a name of the instance, belonging to a particular class.particular class.

2. 2. AllocateAllocate storage for the instance using the storage for the instance using the newnew operator.operator.

// // 1. Declare 3 instances of class 1. Declare 3 instances of class CircleCircle..Circle c1, c2, c3;Circle c1, c2, c3;

// // 2. Allocate using 2. Allocate using newnew, with different initial , with different initial constructions.constructions.c1 = c1 = newnew Circle Circle()();;c2 = c2 = newnew Circle Circle((2.02.0));;c3 = c3 = newnew Circle Circle((3.0, 3.0, "red""red"));;

Circle c4 = new CircleCircle c4 = new Circle()();;// // Combine declare & allocate in one statement, same Combine declare & allocate in one statement, same as:as://// Circle c4;Circle c4;//// c4 = c4 = newnew Circle Circle()();;

Page 36: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

36

Dot OperatorDot Operator To refer to the variables and methods of an object, To refer to the variables and methods of an object,

use use dotdot ‘‘..’’ operator, e.g., operator, e.g.,

// // Declare & allocate an instance of class Declare & allocate an instance of class CircleCircle..Circle c1 = Circle c1 = newnew Circle Circle()(); ;

// // Invoke methods of the class using Invoke methods of the class using dotdot operator. operator.c1.getRadiusc1.getRadius()();;c1.computeAreac1.computeArea()();;

// // Modify public variables with Modify public variables with dotdot operator. operator.c1.radius = 5.0;c1.radius = 5.0;c1.color = c1.color = "green""green";;

MathMath.PI .PI //// Constant Constant PIPI in class in class MathMath..

Page 37: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

37

Methods (Dynamic Behaviors)Methods (Dynamic Behaviors) Methods receive Methods receive argumentsarguments (or parameters), (or parameters),

perform some operations and return a perform some operations and return a single resultsingle result (or (or voidvoid i.e., nothing).i.e., nothing).

You have been using You have been using main()main() method, which is a method, which is a publicpublic method accessible by all classes, takes an method accessible by all classes, takes an array of array of StringString (command-line arguments) as (command-line arguments) as argument, performs the operations specified in the argument, performs the operations specified in the method's body, and return method's body, and return voidvoid (or nothing) to the (or nothing) to the caller.caller.

publicpublic staticstatic voidvoid main main ((StringString[][] args args)) {{ ......method's bodymethod's body...... }}

Page 38: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

38

Method (cont.)Method (cont.) Method naming conventionMethod naming convention: verbs, in mixed case : verbs, in mixed case

with the first letter lowercase and the first letter of with the first letter lowercase and the first letter of each internal word capitalized. E.g., each internal word capitalized. E.g., getBackground()getBackground(), , setColor()setColor()..

Examples:Examples:

publicpublic doubledouble computeArea computeArea () {() { returnreturn radius*radius* radius*radius*MathMath.PI; .PI; }}

Page 39: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

39

Constructor MethodsConstructor Methods A A constructorconstructor is a is a special methodspecial method that shares the that shares the

same name as the class in which it is defined.same name as the class in which it is defined. Constructor is to Constructor is to initialize the instance variablesinitialize the instance variables of of

an object when a new object is first instantiated.an object when a new object is first instantiated. Constructor has no return type (or implicitly return Constructor has no return type (or implicitly return voidvoid). Hence, no ). Hence, no returnreturn statement is needed in the statement is needed in the body of constructor.body of constructor.

Page 40: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

40

OOP Basics - ExampleOOP Basics - Example A class called A class called CircleCircle is declared with: is declared with:

•3 3 constructorconstructor methods, methods,•2 2 private variablesprivate variables radiusradius ( (doubledouble), ), colorcolor ( (StringString))•3 3 public methodspublic methods getRadius()getRadius(), , getColor()getColor(), , computeArea()computeArea(). .

Three instancesThree instances of the class of the class c1c1, , c2c2 and and c3c3 are to be created in are to be created in another class called another class called TestCircleTestCircle..

ClassClass

CircleCircle

double radiusdouble radiusString colorString color

getRadius()getRadius()getColor()getColor()computeArea()computeArea()

C1:CircleC1:Circle

radius=2.0radius=2.0color="blue"color="blue"

methodsmethods

InstancesInstances

C2:CircleC2:Circle

radius=2.0radius=2.0color="red"color="red"

methodsmethods

C3:CircleC3:Circle

radius=1.0radius=1.0color="red"color="red"

methodsmethods

Page 41: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

41

publicpublic classclass Circle Circle {{

privateprivate doubledouble radius; radius; // private variables// private variables privateprivate StringString color; color;

publicpublic Circle Circle ()() // constructors// constructors {{ radius=1.0; color= radius=1.0; color="red""red" }} // overloading// overloading

publicpublic Circle Circle ((doubledouble r r)) {{ radius=r; color= radius=r; color="red""red" }}

publicpublic Circle Circle ((doubledouble r, r, StringString c c)) {{ radius=r; color=c radius=r; color=c }}

publicpublic doubledouble getRadius getRadius ()() // assessor methods// assessor methods {{ returnreturn radius; radius; }}

publicpublic StringString getColor getColor ()() {{ returnreturn color; color; }}

publicpublic doubledouble computeArea computeArea ()() {{ returnreturn radius*radius* radius*radius*MathMath.PI; .PI; }}}}

Page 42: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

42

publicpublic classclass TestCircle TestCircle {{ publicpublic staticstatic voidvoid main main((StringString[][] args args)) {{

Circle c1 = Circle c1 = newnew Circle Circle((2.0, 2.0, "blue""blue"));; SystemSystem.out.println.out.println(( "Radius = ""Radius = " + c1.getRadius + c1.getRadius()() + + " Color = "" Color = " + c1.getColor + c1.getColor()() + + " Area = "" Area = " + c1.computeArea + c1.computeArea())());;

Circle c2 = Circle c2 = newnew Circle Circle((2.02.0));; SystemSystem.out.println.out.println(( "Radius = ""Radius = " + c2.getRadius + c2.getRadius()() + + " Color = "" Color = " + c2.getColor + c2.getColor()() + + " Area = "" Area = " + c2.computeArea + c2.computeArea())());;

Circle c3 = Circle c3 = newnew Circle Circle()();; SystemSystem.out.println.out.println(( "Radius = ""Radius = " + c3.getRadius + c3.getRadius()() + + " Color = "" Color = " + c3.getColor + c3.getColor()() + + " Area = "" Area = " + c3.computeArea + c3.computeArea())());; }}}}

Page 43: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

43

Method OverloadingMethod Overloading More than one methods may share the same name More than one methods may share the same name

as long as they may be distinguished either by the as long as they may be distinguished either by the number of parameters, or the type of parameters. number of parameters, or the type of parameters. E.g.,E.g.,

intint average average((intint n1 n1)) // A// A {{ returnreturn n1; n1; }}intint average average((intint n1, n1, intint n2 n2)) // B// B {{ returnreturn ((n1+n2n1+n2))/2; /2; }}intint average average((intint n1, n1, intint n2, n2, intint n3 n3) ) // C// C {{ returnreturn ((n1+n2+n3n1+n2+n3))/3; /3; }}

averageaverage((11)) // Use A, returns int 1// Use A, returns int 1averageaverage((11, , 22)) // Use B, returns int 1// Use B, returns int 1averageaverage((11, , 22, , 33)) // Use C, returns int 2// Use C, returns int 2

Page 44: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

44

Access ControlAccess Control Access-control modifiers are used to control the Access-control modifiers are used to control the

accessibility (or visibility) of the variables/methods accessibility (or visibility) of the variables/methods by other classes.by other classes.•publicpublic: accessible by any class.: accessible by any class.•privateprivate: accessible only from within the same class.: accessible only from within the same class.

Examples:Examples:

privateprivate doubledouble radius; radius; // // Within the class onlyWithin the class onlypublicpublic intint count; count; // // Accessible by all Accessible by all classesclasses

Page 45: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

45

Information HidingInformation Hiding Variables are usually hidden from outside class, with Variables are usually hidden from outside class, with

modifier modifier privateprivate.. Access to the variables is provided through the Access to the variables is provided through the publicpublic accessor's methods accessor's methods defined in the class, defined in the class, e.g., e.g., getNamegetName()(), , getRadiusgetRadius()(), , comupteAreacomupteArea()()..

In the previous exercise, can you change the In the previous exercise, can you change the radiusradius with with c1.radius=2.0c1.radius=2.0? How to change the ? How to change the radiusradius??

Objects communicate with each others using well-Objects communicate with each others using well-defined interfaces, objects are not allowed to know defined interfaces, objects are not allowed to know how the other objects are implemented – how the other objects are implemented – implementation details are hidden within the implementation details are hidden within the objects themselves.objects themselves.

Rule of thumbRule of thumb: Don't make any variable : Don't make any variable publicpublic without good reason.without good reason.

Page 46: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

46

Get and Set MethodsGet and Set Methods To allow others to read the value of a To allow others to read the value of a privateprivate

variable, the class can provide a “variable, the class can provide a “getget” method (or ” method (or accessor method). A accessor method). A getget method need not expose method need not expose data in the raw format. It can edit the data and data in the raw format. It can edit the data and limit the view of the data others will see.limit the view of the data others will see.

To enable others to modify a To enable others to modify a privateprivate variable, the variable, the class can provide a “class can provide a “setset” method (or mutator ” method (or mutator method). A method). A setset method can provide data validation method can provide data validation (such as range checking), or translate the format of (such as range checking), or translate the format of data used inside the class to another format used by data used inside the class to another format used by outsiders. outsiders.

Page 47: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

47

InheritanceInheritance Classes are organized in strict Classes are organized in strict hierarchyhierarchy. The classes in . The classes in

the lower hierarchy inherit all the variables (attributes) the lower hierarchy inherit all the variables (attributes) and methods (behaviors) from the upper hierarchy, e.g.,and methods (behaviors) from the upper hierarchy, e.g.,

CircleCircle

CylindeCylinderr

radiusradiuscolorcolor

radiusradiuscolorcolorheightheight

StudenStudentt

UndergraduateUndergraduate GraduateGraduate

Yr 1Yr 1 Yr 2Yr 2 Yr 3Yr 3 Yr Yr 44

Page 48: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

48

Superclass and SubclassSuperclass and Subclass The existing class is called The existing class is called superclasssuperclass (or parent (or parent

class, base class). The class derived is called class, base class). The class derived is called subclasssubclass (or child, extended, derived class).(or child, extended, derived class).

In Java, each class has one and only one superclass. In Java, each class has one and only one superclass. Each superclass can have one or many subclasses. Each superclass can have one or many subclasses.

Java does not support multiple inheritance (i.e., Java does not support multiple inheritance (i.e., multiple parents) as in C++.multiple parents) as in C++.

Subclass is not a “subset” of superclassSubclass is not a “subset” of superclass. In fact, . In fact, subclass usually contains subclass usually contains moremore detailed information detailed information (variables and methods) than its superclass.(variables and methods) than its superclass.

To define a subclass, use To define a subclass, use extendsextends operator: operator:

classclass UnderGraduate UnderGraduate extendsextends Student Student {{......}}classclass Cylinder Cylinder extendsextends Circle Circle {{......}}classclass MyApplet MyApplet extendsextends java.applet.Applet java.applet.Applet {{......}}

Page 49: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

49

Inheritance - ExampleInheritance - Example In this exercise, a subclass In this exercise, a subclass

called called CylinderCylinder is derived is derived from superclass from superclass CircleCircle as as shown. Figure out how the shown. Figure out how the subclass subclass CylinderCylinder uses the uses the superclass’s constructors superclass’s constructors (thru the (thru the super()super() method) method) and inherits variables and and inherits variables and methods from its superclass methods from its superclass CircleCircle..Re-useRe-use the the CircleCircle class class defined in the earlier defined in the earlier exercise.exercise.

SuperclassSuperclass

SubclassSubclass

CircleCircle

double radiusdouble radiusString colorString color

getRadius()getRadius()getColor()getColor()computeArea()computeArea()

CylinderCylinder

double heightdouble height

getHeight()getHeight()computeVolume()computeVolume()

Page 50: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

50

publicpublic classclass Circle Circle {{ privateprivate doubledouble radius; radius; // private variables// private variables privateprivate StringString color; color;

publicpublic Circle Circle ()() // constructors// constructors {{ radius=1.0; color= radius=1.0; color="red""red" }} // overloading// overloading

publicpublic Circle Circle ((doubledouble r r)) {{ radius=r; color= radius=r; color="red""red" }}

publicpublic Circle Circle ((doubledouble r, r, StringString c c)) {{ radius=r; color=c radius=r; color=c }}

publicpublic doubledouble getRadius getRadius ()() // assessor methods// assessor methods {{ returnreturn radius; radius; }}

publicpublic StringString getColor getColor ()() {{ returnreturn color; color; }}

publicpublic doubledouble computeArea computeArea ()() {{ returnreturn radius*radius* radius*radius*MathMath.PI; .PI; }}}}

Page 51: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

51

publicpublic classclass Cylinder Cylinder extendsextends Circle Circle {{

privateprivate doubledouble height; height;

publicpublic Cylinder Cylinder ()() {{ supersuper()();; // call superclass Circle()// call superclass Circle() height = 1.0;height = 1.0; }}

publicpublic Cylinder Cylinder ((doubledouble r, r, doubledouble height height) {) { supersuper((rr));; // call superclass Circle(r)// call superclass Circle(r) thisthis.height = height; .height = height; // “this” class// “this” class }}

publicpublic doubledouble getHeight getHeight () {() { returnreturn height; height; }}

publicpublic doubledouble computeVolume computeVolume () {() { returnreturn computeArea computeArea()()*height; *height; }}

}}

Page 52: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

52

publicpublic classclass TestCylinder TestCylinder {{

publicpublic staticstatic voidvoid main main ((StringString[][] args args)) {{

Cylinder c1 = Cylinder c1 = newnew Cylinder Cylinder()();; SystemSystem.out.println.out.println(("Radius=""Radius=" + c1.getRadius + c1.getRadius()() + + " Height="" Height=" + c1.getHeight + c1.getHeight()() + + " Base area="" Base area=" + c1.computeArea + c1.computeArea()() + + " volume=" " volume=" + c1.computeVolume+ c1.computeVolume())());; // Methods getRadius() and computeArea()// Methods getRadius() and computeArea() // inherited from superclass Circle// inherited from superclass Circle

Cylinder c2 = Cylinder c2 = newnew Cylinder Cylinder((5.0, 2.05.0, 2.0));; SystemSystem.out.println.out.println(("Radius=""Radius=" + c2.getRadius + c2.getRadius()() + + " height="" height=" + c2.getHeight + c2.getHeight()() + + " base area="" base area=" + c2.computeArea + c2.computeArea()() + + " volume="" volume=" + c2.computeVolume + c2.computeVolume())());;

}} }}

Page 53: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

53

supersuper and and thisthis Keywords Keywords thisthis can be used to refer to a can be used to refer to a

variable/method in this class, or to call another variable/method in this class, or to call another constructor of the same class. “constructor of the same class. “thisthis” is useful in ” is useful in resolving naming conflict between local variables resolving naming conflict between local variables and instance variables. E.g.,and instance variables. E.g.,

publicpublic classclass Circle Circle {{ privateprivate intint radius; radius;

publicpublic Circle Circle ((intint radius radius)) {{ thisthis.radius = radius; .radius = radius; }}}}

Keyword Keyword supersuper can be used to refer to a can be used to refer to a variable/method of the superclass, or to call a variable/method of the superclass, or to call a constructor of the superclass within the subclass’s constructor of the superclass within the subclass’s constructor (via constructor (via super(...)super(...)).).

Page 54: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

54

Method OverridingMethod Overriding You can You can override override a method inherited from the a method inherited from the

superclass by providing your implementation in the superclass by providing your implementation in the subclass. When an instance of the subclass calls subclass. When an instance of the subclass calls this method, the method in the subclass will be this method, the method in the subclass will be invoked instead of the one in the superclass.invoked instead of the one in the superclass.

ExerciseExercise: Try : Try overridingoverriding the method the method computeArea()computeArea() of class of class CylinderCylinder to compute the surface area of the to compute the surface area of the CylinderCylinder instead of the base area as in its instead of the base area as in its superclass superclass CircleCircle..You can still invoke the You can still invoke the CircleCircle’s ’s computeArea()computeArea(), , instead of the overridden one in the subclass instead of the overridden one in the subclass CylinderCylinder by calling by calling super.computeArea()super.computeArea()..

Page 55: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

55

PackagesPackages A package is a collection of classes (like libraries).A package is a collection of classes (like libraries). Provide a convenient way to organized classes. Eg, Provide a convenient way to organized classes. Eg,

you can put the classes that you developed in you can put the classes that you developed in packages, and distribute the packages.packages, and distribute the packages.

To “locate” a class from a package other than To “locate” a class from a package other than java.langjava.lang, use , use importimport statement, eg, statement, eg,

import java.applet.Appletimport java.applet.Applet // import class Applet from package java.applet// import class Applet from package java.appletimport java.awt.Graphic import java.awt.Graphic // import class Graphic from package java.awt// import class Graphic from package java.awtimport java.awt.*import java.awt.* // import // import allall classes from package java.awt classes from package java.awt // (Abstract Windowing Toolkit)// (Abstract Windowing Toolkit)

Page 56: 1 Java Language Java Basics. 2 Java is Familiar, Simple & Small Java is familiar because it looks like C/C++. Having Java retain the “look and feel” of

56

Java API PackagesJava API Packages java.langjava.lang: contains core Java classes such as : contains core Java classes such as SystemSystem, , StringString,,IntegerInteger. Implicitly imported into . Implicitly imported into every Java program. (i.e. No every Java program. (i.e. No importimport needed). needed).

java.awtjava.awt: Abstract Windowing Toolkit, contains : Abstract Windowing Toolkit, contains classes for GUI components such as classes for GUI components such as ButtonButton, , TextFieldTextField, , ChoiceChoice, , LabelLabel..

java.awt.eventjava.awt.event: for handling events in GUI.: for handling events in GUI. java.appletjava.applet: for supporting Java applets.: for supporting Java applets. java.iojava.io: for input and output streams and files: for input and output streams and files java.sqljava.sql: for accessing relational databases.: for accessing relational databases. java.utiljava.util: utility such as date, vectors, hashing.: utility such as date, vectors, hashing. java.netjava.net: for networking.: for networking. many many others.many many others.