Learn Java in 30 Days Free
-
Upload
miketod113 -
Category
Documents
-
view
237 -
download
0
Transcript of Learn Java in 30 Days Free
-
8/12/2019 Learn Java in 30 Days Free
1/184
1/10
Lecture 1a: Java Introduction
Big companies like IBM are embracing Java far more than most people realize. Half of IBM is busy recoding billions of lines of software to Java. The other half is working tomake Java run well on all platforms, and great on all future platforms .
PBS technology commentator Robert X. Cringely
You'll also become a Java programmer with a lot of potential. Welcome to Java World!
Javas Lineage
Java is related to C++, which is a direct descendent of C. Much of the
character of Java is inherited from these two languages.
From C, Java derives its syntax.
Many of Javas object-oriented features were influenced by C++.
The Java Buzzwords
No discussion of the genesis of Java is complete without a look at the Java buzzwords.
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic
-
8/12/2019 Learn Java in 30 Days Free
2/184
-
8/12/2019 Learn Java in 30 Days Free
3/184
3/10
JAVA IDE
Using JDK you can compile and run java program from command line.o c:> javac HelloWorld. java - compiling here and it will produce
HelloWorld.class i.e. bytecode.o c:>java HelloWorld - It runs java byte code on native machine
Creating, Compiling, Debugging and Execution for these four steps JDK is notuser friendly. IDE is provided for that. A list of IDEs are:
o Eclipse - from IBMo Netbeans.
An Example HelloWorld/**
This is my first java program*/
publ i c cl ass Hel l oWorl dExampl e{
publ i c s tat i c voi d mai n( St r i ng ar gs[ ] ){
Syst em. out . pr i nt l n( "Hel l o Wor l d") ;}
}
Java Source Code Naming Conventions
All java source file should end in .java
Each .java file can contain only one public class
The name of the file should be the name of the public class plus ".java"
Do not use abbreviations in the name of the class
If the class name contains multiple words then capitalize the first letter of eachword ex. HelloWorld.java
-
8/12/2019 Learn Java in 30 Days Free
4/184
-
8/12/2019 Learn Java in 30 Days Free
5/184
5/10
Java Program Style and Layout
Three different indentation styles you can use You can pick a reasonable indentation style and use it consistently in your
programs
Style#1
cl ass Synt ax { / / br ace st ar t s f r om her epubl i c s tat i c voi d mai n( St r i ng ar gs[ ] ) {
i nt aVar i abl e = 5;i f ( aVar i abl e < aFl oat )
Syst em. out . pr i nt l n( "True" ) ;}
}
St yl e #2
cl ass Synt ax{ / / br ace s t ar t spubl i c s tat i c voi d mai n( St r i ng ar gs[ ] ){
i nt aVar i abl e = 5;i f ( aVar i abl e < aFl oat )
Syst em. out . pr i nt l n( "True" ) ;}
}
St yl e#3
cl ass Synt ax{/ / br ace s t ar t spubl i c s tat i c voi d mai n( St r i ng ar gs[ ] )
{i nt aVar i abl e = 5;i f ( aVar i abl e < aFl oat )
Syst em. out . pr i nt l n( "True" ) ;}
}
Naming conventions
Class Naming Uses Capitalized word(s) i.e. Title case
Examples:-HelloWorld, MyList, StudentMark
Wrong:helloWorld, HW (do not use abbreviation)
-
8/12/2019 Learn Java in 30 Days Free
6/184
6/10
Variable and function names
starts with a lowercase letter and after that use Title case
Examples:-
variableAndFunctionNamesaFloat, studentName
Names of constants
All are capital letters and separated by underscore. Example is NAMES_OF_CONSTANTS
Boolean
true, false act like keywords but are boolean constants
public class Bool eanTest { public static void mai n( St r i ng ar gs[ ] ) {
boolean f l ag = 2 > 3;if ( f l ag && true )
Syst em. out . pr i nt l n( " Tr ue" ) ;else
Syst em. out . pr i nt l n( "Fal se" ) ;}
}
Input and Output
Standard Java Output
System.out is standard out in JavaSystem.err is error out in Java
cl ass Out put{publ i c s tat i c voi d mai n( St r i ng ar gs[ ] )
{/ / St andar d out
Syst em. out . pr i nt ( "Pri nt s , but no newl i ne" ) ;Syst em. out . pr i nt l n( "Pr i nt s, adds pl at f or ms newl i ne at end" ) ;doubl e t est = 4. 6;Syst em. out . pr i nt l n( " You can use " + " t he pl us oper at or on "
+ t est + " St r i ng mi xed wi t h number s" ) ;
Syst em. er r . pr i nt l n( "Standar d er r or out put " ) ;}
}
-
8/12/2019 Learn Java in 30 Days Free
7/184
7/10
Output
Pr i nt s, but no l i nef eed Pr i nt s, adds l i nef eed at end You can use t he pl us oper at or on 4. 6 St r i ng mi xed wi t h number sSt andard er r or out put
Standard Java Input
Java assumes that you will be using a GUI for input from the user Hence there isno "simple" way to read input from a user
Scanner class is in jdk 1.5
package l ect ur e01;
import j ava. ut i l . Scanner ;
public class Test I nput { public static void mai n( St r i ng[ ] ar gs ) {
Scanner scanner = new Scanner ( Syst em. in ) ;
Syst em. out . pr i nt ( " Wr i t e your name: " ) ;St r i ng user Name = scanner . next Li ne( ) ;Syst em. out . pr i nt l n( " Your name i s : " + user Name) ;
}}
OutputWr i t e your name: Monzur ur Rahman
Your name i s : Monzur ur RahmanYou t yped: 34
Basic Data Types
cl ass Pr i mi t i veTypes{publ i c s tat i c voi d mai n( St r i ng ar gs[ ] )
{/ / I nt egr al Typesbyt e aByt eVar i abl e; / / 8- bi t sshor t aShor t Var i abl e; / / 16- bi t si nt aI nt Var i abl e; / / 32- bi t s
l ong aLongVar i abl e; / / 64- bi t s/ / Fl oat i ng- Poi nt Typesf l oat aFl oat Var i abl e; / / 32- bi t I EEE 754 f l oatdoubl e aDoubl eVar i abl e; / / 64- bi t I EEE 754 f l oat/ / Charact er Typechar aChar Var i abl e; / / al ways 16- bi t Uni code/ / Bool ean Typesbool ean aBool eanVar i abl e; / / t r ue or f al se}
}
-
8/12/2019 Learn Java in 30 Days Free
8/184
8/10
Operations on Primitive Types
Equality = !=Relational < >=
Unary + -
Arithmetic + - * / %
Pre, postfix increment/decrement ++ --
Shift > >>>
Unary Bitwise logical negation ~
Binary Bitwise logical operators & | ^
cl ass Oper at i ons{publ i c s tat i c voi d mai n( St r i ng ar gs[ ] )
{i nt a = 2;i nt b = +4;i nt c = a + b;i f ( b > a )
Sys tem. out . pr i nt l n( "b i s l ar ger ") ;el se
Sys tem. out . pr i nt l n( "a i s l ar ger ") ;Syst em. out . pr i nt l n( a > 1) ; / / Shi f t r i ght : 1Syst em. out . pr i nt l n( ~a ) ; / / bi t wi se negat i on: - 3Syst em. out . pr i nt l n( a | b) ; / / bi t wi se OR: 6Syst em. out . pr i nt l n( a ^ b) ; / / bi t wi se XOR: 6Syst em. out . pr i nt l n( a & b) ; / / bi t wi se AND: 0}
}
-
8/12/2019 Learn Java in 30 Days Free
9/184
9/10
NaN, + , -
Zero divide with floating-point results in + , -
Overflow results in either + , - .
Underflow results in zero.
An operation that has no mathematically definite result produces NaN - Not a Number
NaN is not equal to any number, including another NaN
cl ass NaN{publ i c s tat i c voi d mai n( St r i ng ar gs[ ] )
{f l oat s i ze = 0;f l oat aver age = 10 / si ze;f l oat i nf i ni t y = 1. 40e38f * 1. 40e38f ;Sys tem. out . pr i nt l n( aver age ) ; / / Pr i nt s I nf i ni t ySys t em. out . pr i nt l n( i nf i ni t y ) ; / / Pr i nt s I nf i ni t y}
}
Casting
cl ass Cast i ng{publ i c s tat i c voi d mai n( St r i ng ar gs[ ] )
{i nt anI nt = 5;f l oat aFl oat = 5. 8f ;aFl oat = anI nt ; / / I mpl i ci t cast s up ar e okanI nt = aFl oat ; / / Compi l e er r or ,
/ / must expl i ci t l y cast downanI nt = ( i nt ) aFl oat ;f l oat er r or = 5. 8; / / Compi l e er r or , 5. 8 i s doubl ef l oat wor ks = ( f l oat ) 5. 8;char c = ( char ) aFl oat ;doubl e aDoubl e = 12D;doubl e bDoubl e = anI nt + aDoubl e; / / anI nt i s cast upt o doubl e,i nt noWay = 5 / 0; / / Compi l e err or , compi l er det ect s
/ / zer o di vi dei nt zer o = 0;i nt t r oubl e = 5 / zer o; / / Some compi l er s may gi ve err or her ei nt not Zer oYet ;not Zer oYet = 0;
-
8/12/2019 Learn Java in 30 Days Free
10/184
10/10
t r oubl e = 5 / not Zer oYet ; / / No compi l e er r or !}
}
Ints and Booleans are Different
cl ass UseBool ean{publ i c s tat i c voi d mai n( St r i ng ar gs[ ] )
{i f ( ( 5 > 4 ) == t r ue )
Syst em. out . pr i nt l n( "J ava' s expl i ci t compar e " ) ;i f ( 5 > 4 )
Syst em. out . pr i nt l n( "J ava' s i mpl i ci t compar e " ) ;i f ( ( 5 > 4 ) ! = 0 ) / / Compi l e er r or
Syst em. out . pr i nt l n( " C way does not wor k" ) ;bool ean cant Cast Fr omI nt ToBool ean = ( bool ean) 0;
/ / compi l e er r ori nt x = 10;i nt y = 5;i f ( x = y ) / / Compi l e er r or
Syst em. out . pr i nt l n( "Thi s does not wor k i n J ava " ) ;}
}
*************** End of Lecture 1a **************
-
8/12/2019 Learn Java in 30 Days Free
11/184
1/13
United International University
Course: CSI 211 Course Title: Object Oriented Programming
Lecture 1b: Array and Control Structure
Arrays
Major differences with C/C++ arrays:
Java arrays are references Java arrays know their size Java checks the bounds of an array when accessed
Java multidimensional arrays need not be rectangular Java array elements are initialized
Exampl e 1: )
publ i c cl ass Si mpl eRef er enceExampl e{publ i c s tat i c voi d mai n( St r i ng ar gs[ ] )
{/ / Ref er ence al l ocat ed, no ar r ay space al l ocat edf l oat [ ] sampl eAr r ay;/ / al l ocat e ar r ay l ocat i ons on heap
sampl eAr r ay = new f l oat [ 12 ] ;/ / I ndexi ng st ar t s at 0 l i ke C/ C++sampl eAr r ay[ 0 ] = 3. 2F;i nt [ ] i nt eger Ar r ay = new i nt [ 3 ] ;
/ / Ref er ence r ef er s t o new ar r ay./ / Ol d ar r ay avai l abl e f or gar bage col l ect i onsampl eAr r ay = new f l oat [ 2 ] ;}
}
-
8/12/2019 Learn Java in 30 Days Free
12/184
2/13
Exampl e 2: )
publ i c cl ass Ar r ayExampl es{publ i c s tat i c voi d mai n( St r i ng ar gs[ ] )
{/ / Two l ocat i ons t o pl ace [ ]i nt i nt egerArr ay[ ] ;i nt [ ] al i as;i nt eger Ar r ay = new i nt [ 10 ] ; / / I ndexed f r om 0 t o 9/ / Not e use of . l engt h t o get ar r ay si zef or ( i nt i ndex = 0; i ndex < i nt eger Ar r ay. l engt h; i ndex++ )
i nt eger Ar r ay[ i ndex ] = 5;al i as = i nt eger Ar r ay; / / Ar r ays ar e r ef er encesal i as[ 3 ] = 10;Syst em. out . pr i nt l n( i nt eger Ar r ay[ 3 ] ) ; / / Pr i nt s 10
i nt eger Ar r ay = new i nt [ 8 ] ;Syst em. out . pr i nt l n( i nt eger Ar r ay[ 3 ] ) ; / / Pr i nt s 0, Why?Sys tem. out . pr i nt l n( al i as [ 3 ] ) ; / / Pr i nt s 10
Syst em. out . pr i nt l n( i nt eger Ar r ay ) ; / / Pr i nt s [ I @5e300868}}
Arrays, References, Memory Leaks Arrays are references!
Garbage collection reclaims arrays that can not be accessed! References are initialized to null When done with a reference set it to null
publ i c cl assAr r ayExampl es{publ i c s tat i c voi d mai n( St r i ng ar gs[ ] )
{i nt [ ] i nt eger Ar r ay = new i nt [ 4 ] ;i nt eger Ar r ay[ 1 ] = 12
i nt egerAr r ay = new i nt [ 2 ] ; / / Memor y Leak - No!i nt eger Ar r ay[ 1 ] = 5;i nt [ ] al i asFor Ar r ay = i nt eger Ar r ay;al i asFor Ar r ay[ 1 ] = 10;Syst em. out . pr i nt l n( i nt eger Ar r ay[ 1 ] ) ; / / Pr i nt s 10}
}
-
8/12/2019 Learn Java in 30 Days Free
13/184
3/13
HEAP ALLOCATION
i nt [ ] i nt eger Ar r ay = new i nt [ 4 ] ;
i nt eger Ar r ay[ 1 ] = 12
i nt egerAr r ay = new i nt [ 2 ] ; / / Memor y Leak - No!
i nt eger Ar r ay[ 1 ] = 5;
i nt [ ] al i asFor Ar r ay = i nt eger Ar r ay;
al i asFor Ar r ay[ 1 ] = 10;
Memory Problems in C/C++
Memory Leaks
Memory that program has allocated but can no longer accessint* trouble = new int( 5 );trouble = new int( 8 );
-
8/12/2019 Learn Java in 30 Days Free
14/184
4/13
Dangling References
Two or more pointers point to the same memory on the heap Using one of the pointers the memory is deallocated Second pointer can still access the memory Estimates are that up to 40% of development time in C/C++ are spent dealing
with these two problems
Java Solution
No pointers No explicit deallocation of memory When memory can no longer be accessed, garbage collection eventually
reclaims the memory
J ava' s sol ut i on i s mor e dynami c, f l exi bl e, and saf er t han C/ C++
Array Bounds and Initial Values
Any access of an array element is check at runtime to insure the element index isvalid
The example below shows what happens when accessing an illegal index. The lower index of an array is always zero All array elements are given an initial value The actual value given depend on the type
-
8/12/2019 Learn Java in 30 Days Free
15/184
5/13
publ i c cl ass BoundsAndI ni t i al Val ueExampl e{publ i c s tat i c voi d mai n( St r i ng ar gs[ ] )
{i nt [ ] dat a = new i nt [ 2] ;
Syst em. out . pr i nt l n( "Dat a[ 1] = " + dat a[ 1] ) ;dat a[ 12] = 2;Syst em. out . pr i nt l n( "Af t er assi gnment " ) ;}
}Output
Dat a[ 1] = 0 j ava. l ang. Ar r ayI ndexOut Of BoundsExcept i on
atBoundsAndI ni t i al Val ueExampl e. mai n( BoundsAndI ni t i al Val ueExampl e. j ava: 9)
Array Initializer's One can initialize arrays to a list of values The syntax is slightly different for declaration statements and assignments There is no way to indicate repeated values in the initializer
publ i c c l as s I ni t i al i z i ngAr r ays{publ i c s tat i c voi d mai n( St r i ng ar gs[ ] )
{/ / Shor t Decl ar at i on synt axi nt [ ] odds = {1, 3, 5, 7, 9 };char [ ] vowel s = { ' a' , ' e' , ' i ' , ' o' , ' u' };St r i ng[ ] names;/ / Assi gnment synt ax - new i n J DK 1. 1. xnames = new St r i ng[ ] { "Sam" , " Sal l y", " Pet e" };/ / Can use l onger synt ax i n decl ar at i onschar [ ] abc = new char [ ] { ' a' , ' b' , ' c ' };/ / You can not use shor t synt ax i n assi gnment sdoubl e[ ] t r oubl e;
t r oubl e = { 1. 2, 2. 3, 5. 4 }; / / Compi l er Er r or}
}
-
8/12/2019 Learn Java in 30 Days Free
16/184
-
8/12/2019 Learn Java in 30 Days Free
17/184
7/13
OutputFound 7 at : 3One: 1
Stringspubl i c cl ass St r i ngExampl e{
publ i c s tat i c voi d mai n( St r i ng ar gs[ ] ){
St r i ng f i r st Name = " Roger " ;St r i ng l ast Name = " Whi t ney " ;St r i ng f ul l Name = f i r st Name + l ast Name;Syst em. out . pr i nt l n( f ul l Name ) ;f i r st Name = f i r st Name. t oLower Case( ) ;l ast Name = l ast Name. t oUpper Case( ) ;Syst em. out . pr i nt l n( f i r st Name ) ;f i r s tName = f i r s tName. t r i m( ) ; / / t r i m l eadi ng, t ra i l i ngl ast Name = l ast Name. t r i m( ) ; / / whi t e spacel ast Name = l ast Name. r epl ace( ' I ' , ' a' ) ;Syst em. out . pr i nt l n( f i r st Name + l ast Name ) ;St r i ng f l oat AsSt r i ng = St r i ng. val ueOf ( 13. 4e+5f ) ;Syst em. out . pr i nt l n( f l oat AsSt r i ng ) ;
}}
OutputRoger Whi t neyr oger
r oger WHaTNEY1. 34e+06
String Operations
charAt(int) replace(char,char)
compareTo(String) startsWith(String)
concat(String) substring(int,int)
equals(Object) toUpperCase()
equalsIgnoreCase(String) trim()
length() valueOf(double)
-
8/12/2019 Learn Java in 30 Days Free
18/184
8/13
String comparison == and Strings
publ i c cl ass St r i ngTest{publ i c s tat i c voi d mai n( St r i ng[ ] ar gs )
{St r i ng me = " Roger " ;
i f ( me == " Roger " )Syst em. out . pr i nt l n( "Yes, I am me" ) ;
el seSyst em. out . pr i nt l n( "No, I am not me?" ) ;
St r i ng shor t Name = me. subst r i ng( 0, 3 ) ;Syst em. out . pr i nt l n( shor t Name ) ;
i f ( shor t Name == " Rog" )System. out . pr i nt l n( "Ver y Good" ) ;
el seSyst em. out . pr i nt l n( "Troubl e her e" ) ; / / How i s t hi s possi bl e?
i f ( short Name. equal s( "Rog" ) )Syst em. out . pr i nt l n( "Do i t t hi s way" ) ;
}}
OutputYes, I am meRogTrouble hereDo it this way
String variables are references to objects. The == operator checks to see if twostring references refer to the same memory location.
i f ( me == " Roger " )Syst em. out . pr i nt l n( "Yes, I am me" ) ;
el seSyst em. out . pr i nt l n( "No, I am not me?" ) ;
Compilers are allowed, but not required to store equal strings in the same memorylocation. The comparison above checks to see if the two variables refer to thesame memory location. Since me was initialized with a string literal the compilerwas smart enough to store the two strings in the same location.
In the comparison:i f ( shor t Name == " Rog" )
-
8/12/2019 Learn Java in 30 Days Free
19/184
9/13
shortName was not initialized with a literal, so the compiler did not know to store in thesame location as "Rog". Thus this comparison is false !
The equals met hod compar es t he t wo st r i ngs t o det er mi ne i f t heyhave t he same l engt h and ar e t he same char act er by char act er .
Reading Command Line Arguments
publ i c cl ass CommandLi neExampl e{
publ i c s tat i c voi d mai n( St r i ng ar gs[ ] ){
Syst em. out . pr i nt l n( "Ar gs l engt h: " + ar gs. l engt h ) ;f or ( i nt k = 0; k < args. l engt h; k++ )
{ Syst em. out . pr i nt l n( " Ar gument " + k + " \ t " + ar gs[ k ] ) ;};Fl oat secondAr gument = Fl oat . val ueOf ( ar gs[ 1 ] ) ;Syst em. out . pr i nt l n( secondAr gument ) ;
}}
Sample Session Running above Programr ohan 16- > j ava CommandLi neExampl e 1 2 3 4 5Ar gs l engt h: 5Argument 0 1Argument 1 2Argument 2 3Argument 3 4Argument 4 52
-
8/12/2019 Learn Java in 30 Days Free
20/184
10/13
Control Structures
Contains all the standard C/C++ control structures
publ i c cl ass Cont r ol{publ i c s tat i c voi d mai n( St r i ng ar gs[ ] )
{i nt a = 5;i nt b = 10;i f ( a > b ) Syst em. out . pr i nt l n( "a i s bi gger ") ;
i f ( a > b )Syst em. out . pr i nt l n( "a i s bi gger " ) ;
el seSyst em. out . pr i nt l n( "b i s bi gger " ) ;
swi t ch ( a )
{ / / Cont r ol l i ng expr essi on conver t ed t o i ntcase 4:b++;br eak;
case 10:b- - ;br eak;
def aul t : / / opt i onalSyst em. out . pr i nt l n( "Def aul t act i on" ) ;
};whi l e ( a < b )
{a++;};
One more examplef or ( i nt l oop = 0; l oop < a; l oop++ )
{Syst em. out . pr i nt l n( a ) ;};
Syst em. out . pr i nt l n( l oop ) ; / / Er r or , l oop does not/ / exi s t here
do{Sys tem. out . pr i nt l n( a- - ) ;Syst em. out . pr i nt l n( b ) ;}
whi l e ( a > b ) ;i nt max = ( a > b ) ? a : b;i f ( ( a > 5 ) && ( b < 10 ) )
Syst em. out . pr i nt l n( "Good" ) ;a += ( a = 5 ) ;}
}
-
8/12/2019 Learn Java in 30 Days Free
21/184
11/13
Jump Statements
break
Exits out of a loop or switch statement Unlabeled break exits out of the innermost loop or switch Use labeled break to exit out of nested loops or switch
publ i c cl ass Br eakExampl e {publ i c s t at i c voi d mai n( St r i ng ar gs[ ] ) {
f or ( i nt r ow = 0; r ow < 5; r ow++ ) {f or ( i nt col umn = 0; col umn < 4 ; col umn++ ) {
Syst em. out . pr i nt l n( r ow + "\ t " + col umn ) ;i f ( ( ( r ow + col umn) % 2 ) == 0 )
br eak;Sys t em. out . pr i nt l n( " Af t er i f " ) ;
}};Out er :f or ( i nt r ow = 0; r ow < 5; r ow++ ) {
f or ( i nt col umn = 0; col umn < 4; col umn++ ) {Syst em. out . pr i nt l n( r ow + "\ t " + col umn ) ;i f ( ( ( r ow + col umn) % 2 ) == 0 )
br eak Out er;Sys t em. out . pr i nt l n( " Af t er i f " ) ;
}}
}}Output (Read Down Column First)0 0 3 0
1 0 After if
After if 3 1
1 1 4 0
2 0 0 0
-
8/12/2019 Learn Java in 30 Days Free
22/184
12/13
continue
A continue statement skips to the end of the current loop's body The loop's boolean expression is then evaluated
Methods (Functions)
What are called "functions" in C are called "methods" in Java
Note we do not have to forward declare methods, addOne is used before it is declared
publ i c cl ass Sampl eFunct i on {publ i c st at i c i nt subt r act One( i nt decr easeMe ) {r et ur n decreaseMe - 1;
}publ i c s t at i c voi d mai n( St r i ng[ ] ar gs ) {
i nt st ar t Val ue = 5;i nt smal l er = subt r act One( st ar t Val ue ) ;i nt l ar ger = addOne( st ar t Val ue );Syst em. out . pr i nt l n( " smal l er = " + smal l er + " \ n" +
"l ar ger = " + l ar ger ) ;}publ i c st at i c i nt addOne( i nt i ncr easeMe ) {
r et ur n i ncr easeMe + 1;}
}
Outputsmal l er = 4l arger = 6
Parameter Passing - By value only
In Java all parameters are passed by value
The method gets a copy of the parameter Changes to a parameter in a method are valid only in the method
publ i c cl ass Test Par amet er{publ i c s tat i c voi d mai n( St r i ng[ ] ar gs )
{i nt st ar t Val ue = 5;noChange( st ar t Val ue ) ;Syst em. out . pr i nt l n( s t ar t Val ue ) ;
-
8/12/2019 Learn Java in 30 Days Free
23/184
13/13
}publ i c st at i c voi d noChange( i nt f i xed )
{f i xed = f i xed + 10;}
}
Output5
Final variable
A final variable is a variable which has been initialized to a fixed value which
cannot be changed after initialization.
In older programming languages, a final variable would be called a constant
f i nal s t at i c Poi nt or i gi n = new Poi nt ( 0, 0) ;
*************** End of Lecture 1b **************
-
8/12/2019 Learn Java in 30 Days Free
24/184
1/11
United International University
Course: CSI 211 Course Title: Object Oriented Programming
Lecture 2a: Class and Object
Object-Oriented Programming (OOP) C, PASCAL, BASIC Procedural language In Procedural language data and operation are separate Java is OOP where approach is in term of classes
Two Paradigms in OOP
All computer programs consist of two elements: code and data. Furthermore, a
program can be conceptually organized around its code or around its data. That
is, some programs are written around what is happening and others are written
around who is being affected. These are the two paradigms that govern how
an OOP program is constructed.
Abstraction in OOP
In OOP ( Object Oriented Programming ) , Abstraction facilitates the easy
conceptualization of real world objects into the software program.
Humans manage complexity through abstraction. For example, people do not
think of a car as a set of tens of thousands of individual parts. They think of it as
a well-defined object with its own unique behavior. This abstraction allows
people to use a car to drive to the grocery store without being overwhelmed by
the complexity of the parts that form the car. They can ignore the details of how
the engine, transmission, and braking systems work. Instead they are free to
utilize the object as a whole..
The Three OOP Principles
-
8/12/2019 Learn Java in 30 Days Free
25/184
2/11
Encapsulation
o Encapsulation is the mechanism that binds together code and the data
it manipulates, and keeps both safe from outside interference and
misuse.
o Encapsulation guarantees the integrity of the data contained in the
object.
Inheritance
o Inheritance is the process by which one object acquires the properties
of another object. This is important because it supports the concept of
hierarchical classification.
o Inheritance provides a powerful and natural mechanism for organizing
and structuring your softwareo classes inherit state and behavior from their super classes.
Polymorphism
o Polymorphism (from the Greek, meaning many forms) is a feature
that allows one interface to be used for a general class of actions. The
specific action is determined by the exact nature of the situation.
o More generally, the concept of polymorphism is often expressed by
the phrase one interface, multiple methods. This means that it is
possible to design a generic interface to a group of related activities.
o Consider a stack. You might have a program that requires three types
of stacks. One stack is used for integer values, one for floating-point
values, and one for characters. The algorithm that implements each
stack is the same, even though the data being stored differs. In a non
object-oriented language, you would be required to create three
different sets of stack routines, with each set using different names.
However, because of polymorphism, in Java you can specify a general
set of stack routines that all share the same names.
OOP Terms to describe language
Class
-
8/12/2019 Learn Java in 30 Days Free
26/184
3/11
o A class is a blueprint or prototype from which objects are created. Object
o An object is a software bundle of related state and behavior.
o Software objects are often used to model the real-world objects that
you find in everyday life.
Interface
o An interface is a contract between a class and the outside world. When
a class implements an interface, it promises to provide the behavior
published by that in interface.
Information Hiding
o purpose of hiding is to make inaccessible certain details that should
not affect other parts of a system. Hierarchy
o the mapped relationships of sub- and super classes is known as a
hierarchy.
Package
o A package is a namespace for organizing classes and interfaces in a
logical manner.
o Placing your code into packages makes large software projects easier
to manage.
Basic Terms
Java field method
C++ data member member function
Smalltalk instance variable method
C ??? function
Example of a class
o Class member refers to either a field or method
-
8/12/2019 Learn Java in 30 Days Free
27/184
4/11
publ i c cl ass BankAccount{
publ i c f l oat bal ance = 0. 0F; / / f i el dpubl i c voi d deposi t ( f l oat amount ) / / met hod{
bal ance += amount ;}}
Java Comparisons to C++
Similar class syntax and structure No multiple inheritance, uses interfaces instead Functions are virtual by default Constructors are much simpler Destructors are not need Packages provide separate name spaces for classes
Fields Each object has its own copy of the fields defined in the class, that is
richStudent and poorInstructor have different values for the field balance.
In this regard, classes are like C/C++ structs. The fields in an object exist as long as the object exists
publ i c cl ass BankAccount{
publ i c f l oat bal ance = 0. 0F;}publ i c cl ass RunBank{
publ i c s tat i c voi d mai n( St r i ng ar gs[ ] ){
Syst em. out . pr i nt l n( "Start mai n " ) ;BankAccount r i chSt udent = new BankAccount ( ) ;r i chSt udent . bal ance = ( f l oat ) 100000;BankAccount poor I nst r uct or = new BankAccount ( ) ;poorI nst r uct or. bal ance = 5. 10F;Syst em. out . pr i nt l n( "St udent Bal ance: " +
r i chSt udent . bal ance ) ;Syst em. out . pr i nt l n( "Prof Bal ance: " + poor I nst r uct or . bal ance ) ;
}}
-
8/12/2019 Learn Java in 30 Days Free
28/184
-
8/12/2019 Learn Java in 30 Days Free
29/184
6/11
When a method change the value of a field, the change remains in effect after
the method ends
The toString() Standard
When required Java sends toString() message to objects to convert them tostrings
This happens in println() and when adding to strings
In println( richStudent ) the toString() method is used to convert richStudent to astring
publ i c cl ass RunBank{
publ i c s tat i c voi d mai n( St r i ng ar gs[ ] ){
BankAccount r i chSt udent = new BankAccount ( ) ;BankAccount poor I nst r uct or = new BankAccount ( ) ;r i chSt udent . deposi t ( 10000F) ;poor I nst r uctor. deposi t ( 5. 10F ) ;St r i ng pr of Bal ance = "Prof : " + poor I nst r uct or ;Syst em. out . pr i nt l n( pr of Bal ance ) ;Syst em. out . pr i nt l n( "Prof : " + poor I nst r uctor ) ;Syst em. out . pr i nt l n( r i chSt udent ) ;
}}
OutputProf : Account Bal ance: 5. 1Prof : Account Bal ance: 5. 1Account Bal ance: 10000
Initializing Fields
There are three ways in Java to give a field an initial value: Direct Assignment Instance Initialization Block Constructors
Direct Assignment
publ i c cl ass BankAccount{
-
8/12/2019 Learn Java in 30 Days Free
30/184
7/11
publ i c f l oat bal ance = 0. 0F;publ i c voi d deposi t ( f l oat amount ){
bal ance += amount ;}publ i c St r i ng t oSt r i ng( ){
r et ur n " Account Bal ance: " + bal ance;}
}
Instance Initialization Blocks
Instance initialization blocks are indicated by blocks of code inside the class, butoutside any method.
Whenever an object is created from a class the code in each instance initialization block is executed. If there is more than one instance initialization block they areexecuted in order, from top to bottom of the class.
Use initialization blocks when the initialization cannot be done in a simpleassignment and needs no extra input parameters.
Direct assignment and constructors are used far more often than initialization blocks.
publ i c cl ass TaxAccount{
publ i c doubl e bal ance;
{ / / I ns t ance I ni t i al i z at i on bl ockf l oat baseTaxRat e = . 33F;f l oat companySi ze = 1. 24F;
bal ance = baseTaxRat e * companySi ze -Mat h. si n( baseTaxRat e ) + . 013f ;
}publ i c st at i c voi d mai n( St r i ng[ ] ar gs ) / / Test met hod{
TaxAccount x = new TaxAccount ( ) ;Syst em. out . pr i nt l n( x. bal ance) ;
}}
Output0. 09815697215174707
Initializing Fields - Constructors
-
8/12/2019 Learn Java in 30 Days Free
31/184
-
8/12/2019 Learn Java in 30 Days Free
32/184
9/11
Implicit Constructors If a class has no constructor the compiler generates an implicit constructor with
no arguments for the class. If a class has any constructor, the compiler will not generate the implicit
constructor. If you add a constructor to an existing class, you may need to also add a
constructor with no arguments.
Order of Initialization
When you create an object the direct assignment of fields and instance initialization blocks are done in order from top to bottom of class, then the constructor is executed
publ i c cl ass Or der Exampl e{
i nt aFi el d = 1;{
Syst em. out . pr i nt l n( "Fi r st bl ock: " + aFi el d ) ;aFi el d++;
}publ i c Or der Exampl e( ){
Syst em. out . pr i nt l n( "St ar t Const r uctor: " + aFi el d ) ;aFi el d++;Syst em. out . pr i nt l n( "End Const r uct or : " + aFi el d ) ;
}
{Syst em. out . pr i nt l n( "Second bl ock: " + aFi el d );aFi el d++;
}
publ i c s t at i c voi d mai n( St r i ng ar gs[ ] ){Or der Exampl e t est = new Or der Exampl e( ) ;}
}Output
Fi rs t bl ock: 1Second bl ock: 2St ar t Const r uct or : 3End Const r uct or: 4
Order of Class Elements Layout
Fields must be declared before they are used in an initialization block
-
8/12/2019 Learn Java in 30 Days Free
33/184
10/11
Guidelines suggest placing all field declaration in one location place all fields at the beginning of the class or place all fields at the end of the class
publ i c cl ass Or der Exampl e{
publ i c Or der Exampl e( ){
a = 8; / / OK}
{a = 4; / / Compi l e Er r or
}
i nt a = 1;
publ i c i nt get C( )
{ r et ur n c;}
i nt c = 3;
{a = 4;
}}
Overloading Methods The signature of a method is its name with number, type and order of its
parameters. The return type is not part of the signature of a method. Two methods in the same class can have the same name if their signatures are
different.
publ i c cl ass Over Load{
publ i c voi d same( ) {
Syst em. out . pr i nt l n( "No ar gument s" ) ;}publ i c voi d same( i nt f i r st Ar gument ) {
Syst em. out . pr i nt l n( "One i nt ar gument s" ) ;}publ i c voi d same( char f i r st Ar gument ) {
Syst em. out . pr i nt l n( " One char ar gument s" ) ;}publ i c i nt same( i nt f i r st Ar gument ) { / / Compi l e Er r or
Syst em. out . pr i nt l n( " One char ar gument s" ) ;
-
8/12/2019 Learn Java in 30 Days Free
34/184
11/11
r et ur n 5;}publ i c voi d same( char f i r st Ar gument , i nt s econdAr gument ) {
Syst em. out . pr i nt l n( "char + i nt ar gument s" ) ;}publ i c voi d same( i nt f i r st Ar gument , char s econdAr gument ) {
Syst em. out . pr i nt l n( "i nt + char ar gument s" ) ;}
}
this
"this" refers to the current object.
.
publ i c cl ass BankAccount{
publ i c f l oat bal ance;publ i c BankAccount ( f l oat i ni t i al Bal ance ){
t hi s. bal ance = i ni t i al Bal ance; / / do not need t hi s}publ i c BankAccount ( i nt bal ance ){
t hi s. bal ance = bal ance; / / we must need t hi s her e
}publ i c voi d deposi t ( f l oat amount ){
bal ance += amount ; / / ok her e}publ i c St r i ng t oSt r i ng( ){
r et ur n " Account Bal ance: " + bal ance;}
}
*************** End of Lecture 2a **************
-
8/12/2019 Learn Java in 30 Days Free
35/184
1/11
United International University
Course: CSI 211 Course Title: Object Oriented Programming
Lecture 2b: Class and Object variables and references
Access Levels for Fields and Methods
publicMembers declared public are accessible anywhere the class is accessible
protectedMembers declared protected are directly accessible to any subclasses, and directly
accessible by code in the same package
privateMembers declared private are accessible only in the class itself
publ i c cl ass AccessLevel s{
publ i c i nt publ i cObj ectVar i abl e ;pr ot ect ed f l oat pr ot ect edObj ect Var i abl e = 10;pr i vat e i nt [ ] pr i vat eObj ectVar i abl e;i nt packageAcceess = publ i cObj ect Var i abl e;publ i c AccessLevel s ( i nt st ar t Val ue )
{ Syst em. out . pr i nt l n( " St ar t Const r uctor" ) ;pr i vat eObj ect Var i abl e = new i nt [ st ar t Val ue ] ;
}publ i c voi d sampl eMet hod( i nt val ue ){
Syst em. out . pr i nt l n( " I n met hod" ) ;pr i vat eObj ect Var i abl e[ 1 ] = val ue;
}}publ i c cl ass Test AccessLevel s{
publ i c s tat i c voi d mai n( St r i ng ar gs[ ] ){
AccessLevel s t est = new AccessLevel s ( 11 ) ;t est . publ i cObj ect Var i abl e = 100; / / Okt est . pr otect edObj ect Var i abl e= 100; / / Okt est . pr i vat eObj ect Var i abl e[ 1 ] = 100; / / Compi l e Er r ort est . packageAcceess = 100; / / Ok
}}
-
8/12/2019 Learn Java in 30 Days Free
36/184
2/11
Class Names, Packages, Import, CLASSPATH
Each class belongs to a "package". Packages are used to group related classes. A package creates a name space. Classes in different packages can have the same
name.
To put a class in a package, place the statement:
package packageName;
at the beginning of the source file containing the class.
Example
package EDU. sdsu. r oger ;publ i c cl ass Sampl e {
publ i c voi d hel l o( ) {Syst em. out . pr i nt l n( "Hel l o f or package sdsu. r oger " ) ;
}}
Package names are separated into components, which are separated by "."I n t he above exampl e t he component s ar e "EDU" , " sdsu", and "r oger
Package Examplepackage EDU. sdsu. r oger ;
publ i c cl ass Sampl e {publ i c voi d hel l o( ) {
Syst em. out . pr i nt l n( "Hel l o f or package sdsu. r oger " ) ;}
}
The class must be in a file named "Sample.java" Place file "Sample.java" in a directory called "roger" Place directory "roger" in a directory called "sdsu" Place directory "sdsu" in a directory "EDU"
The directory "EDU" can be placed anywhere, for completeness of the example I place itin the directory "/home/ma/whitney/java"
Make sur e t hat " / home/ ma/ whi t ney/ j ava" i n t he CLASSPATH envi r onmentvar i abl e
-
8/12/2019 Learn Java in 30 Days Free
37/184
3/11
Import Statement
The import statement allows you to use short class names
Both the examples below will compile and runWith Import, Short Namei mpor t EDU. sdsu. r oger . Sampl e;publ i c cl ass Test Package {
publ i c s tat i c voi d mai n( St r i ng ar gs[ ] ) {Sampl e me = new Sampl e( ) ;me. hel l o( ) ;
}}
Without Import, Full Name
publ i c cl ass Test Package {publ i c s tat i c voi d mai n( St r i ng ar gs[ ] ) {EDU. sdsu. r oger . Sampl e me =
new EDU. sdsu. r oger . Sampl e( ) ;me. hel l o( ) ;
}}
Object Variables are References
Two objects references, sam and samTwin, referencing the same object. This isdemonstrated by using the samTwin reference to change the value of the field grade, andusing the reference sam to display the new value.
publ i c cl ass St udent{
publ i c char gr ade;}
publ i c cl ass Poi nt er Test{
publ i c s tat i c voi d mai n( St r i ng ar gs[ ] ){
St udent sam = new St udent ( ) ;sam. gr ade = ' A' ;St udent samTwi n = sam;samTwi n. gr ade = ' C' ;Syst em. out . pr i nt l n( sam. gr ade ) ;
}}OutputC
-
8/12/2019 Learn Java in 30 Days Free
38/184
4/11
Parameter Passing & Objectspubl i c cl ass St udent{
publ i c char gr ade;}publ i c cl ass Test Par amet er{
publ i c s tat i c voi d mai n( St r i ng ar gs[ ] ){
St udent sam = new St udent ( ) ;sam. gr ade = ' C' ;changeRef er ence( sam ) ;Syst em. out . pr i nt l n( sam. gr ade ) ;changeSt at e( sam ) ;Syst em. out . pr i nt l n( sam. gr ade ) ;
}publ i c st at i c voi d changeSt at e( St udent l ucky ){
l ucky. gr ade = ' A' ;}publ i c st at i c voi d changeRef er ence( St udent unl ucky ){unl ucky = new St udent ( ) ; / / Par amet er Passi ng - By val ue onl yunl ucky. gr ade = ' A' ;}
}OutputCA
Static Qualifier
Static Fields
There is only one copy of a static field All objects created from the class reference the same copy of a static field A static field exists before creating an object of the class
publ i c c l ass St at i cFi el ds{
publ i c st at i c i nt s i ze = 10;publ i c voi d i ncr easeSi ze( i nt i ncrement ){
si ze = si ze + i ncr ement ;}
}publ i c cl ass DemoSt at i cFi el ds{
-
8/12/2019 Learn Java in 30 Days Free
39/184
5/11
publ i c st at i c voi d mai n( St r i ng[ ] ar gument s ){
Syst em. out . pr i nt l n( " Si ze " + St at i cFi el ds. s i ze ) ;St at i cFi el ds t op = new St at i cFi el ds( ) ;St at i cFi el ds bot t om = new St at i cFi el ds( ) ;t op. si ze = 20;Syst em. out . pr i nt l n( "Si ze " + bot t om. si ze ) ;
}}OutputSi ze 10Si ze 20
Static Methods (Class Methods)
Static methods can only access static fields and other static methods in the class Static methods can be referenced via an object or the class
publ i c cl ass St at i cMet hods{
publ i c st at i c i nt s i ze = 10;publ i c stat i c voi d i ncreaseSi ze( i nt i ncr ement ){
si ze = si ze + i ncr ement ;}
}publ i c cl ass DemoSt at i cMet hods{
publ i c st at i c voi d mai n( St r i ng[ ] ar gument s ){
St at i cMet hods. i ncr easeSi ze( 30 ) ; / / Not e use of cl ass nameSyst em. out . pr i nt l n( "Si ze " + St at i cMet hods. si ze ) ;St at i cMet hods t op = new St at i cMet hods( ) ;t op. i ncreaseSi ze( 20 ) ;Syst em. out . pr i nt l n( "Si ze " + St at i cMet hods. si ze ) ;
}}OutputSi ze 40Si ze 60
Static Initialization Blocks
A static initialization block is an initialization block preceded with the quantifier"static".
A static initialization block is normally executed only once each time your program is run.
-
8/12/2019 Learn Java in 30 Days Free
40/184
UIU Lecture 2b, CSI 211 6/11
It will be executed before any object is created or any reference is to the class isactually made in your program.
If more than one static block exists in the class, then they are executed in order,from top to bottom of the class.
The static block can only reference static methods and static fields. Any staticfield referenced in the static block must be declared before the static block. Thisrestriction does not hold for static methods.
publ i c cl ass St at i cFi el ds {publ i c st at i c i nt s i ze = 10;st at i c { / / Run when cl ass i s f i r st l oaded
si ze = cl assMet hod( 20) ;
Sys tem. out . pr i nt l n( s i ze ) ;}publ i c st at i c i nt cl assMet hod( i nt val ue ) {
Syst em. out . pr i nt l n( "I n cl ass met hod" ) ;r et ur n val ue + 10;
}}publ i c cl ass Test St at i cFi el ds {
publ i c s tat i c voi d mai n( St r i ng ar gs[ ] ) {Syst em. out . pr i nt l n( " St ar t Test " ) ;St at i cFi el ds t est = new St at i cFi el ds ( ) ;St at i cFi el ds secondObj ect = new St at i cFi el ds ( ) ;St at i cFi el ds. s i ze = 100;Sys tem. out . pr i nt l n( t es t . s i ze ) ; / / Pr i nt 100
}}OutputStart TestI n cl ass met hod30100
Main method There is nothing magic about the method "public static void main( String[] args
)." When you execute a class with the command "java className" The JVM
looks for a method called main with the exact signature and return type i.e."public static void main( String[] args ).
If the main does not have the proper signature and return time, the JVM willreport an error. So the main in OddMain below can not be used to start the class.
-
8/12/2019 Learn Java in 30 Days Free
41/184
UIU Lecture 2b, CSI 211 7/11
However, the method "main" can be called from your code like any other staticmethod, as is done in the next example. This does mean that your program canhave multiple entry points, as the next example shows.
publ i c cl ass Top {publ i c st at i c voi d mai n( St r i ng[ ] ar gument s ) {
Syst em. out . pr i nt l n( "I n t op mai n" ) ;Bot t om. mai n( ar gument s ) ;
}publ i c st at i c voi d pr i nt ( ) {
Syst em. out . pr i nt l n( " I n t op" ) ;}
}publ i c cl ass Bot t om {
publ i c st at i c voi d mai n( St r i ng[ ] ar gument s ) {Syst em. out . pr i nt l n( "I n bot t om mai n" ) ;
Top. pr i nt ( ) ;OddMai n. mai n( ar gument s ) ;
}
}publ i c cl ass OddMai n {publ i c st at i c i nt mai n( St r i ng[ ] ar gument s ) {
/ / s i gnat ur e di f f er entSyst em. out . pr i nt l n( "I n odd mai n" ) ;
Top hat = new Top( ) ;hat . pr i nt ( ) ;r et ur n 5;
}}
Constant Fields
Declaring a field final means that it can only be set once
publ i c cl ass Const ant s{
pr ot ect ed f i nal i nt SI ZE = 10;pr ot ect ed f i nal i nt [ ] CLASS_ARRAY = new i nt [ SI ZE ] ;pr ot ect ed f i nal i nt NO_VALUE_YET; / / bl ank f i nalpubl i c voi d aMet hod( i nt i nput , f i nal f l oat FI XED){
f i nal i nt NEW_FEATURE = 123;f i nal i nt ALSO_FI XED = i nput ;CLASS_ARRAY[ 3 ] = i nput ;
}
publ i c Const ant s( i nt aVal ue ){
NO_VALUE_YET = aVal ue;}
publ i c s tat i c voi d mai n( St r i ng ar gs[ ] ){
-
8/12/2019 Learn Java in 30 Days Free
42/184
UIU Lecture 2b, CSI 211 8/11
Const ant s t est = new Const ant s( 5) ;t est . aMet hod( 13, 2. 2f ) ;Syst em. out . pr i nt l n( t est . NO_VALUE_YET ) ; / / Pr i nt s 5
}}
Blank Final Rules A blank final is a final variable declaration that lacks an initializer A blank final must be assigned exactly once A blank final class (static) variable must be assigned by one static initialization
block
blank final class variable can not be assigned in more than one static
initialization block
A blank final instance variable can not be assigned in a non-static initialization
block and a constructor
publ i c cl ass St at i cConst ant s{
pr ot ec ted s ta t i c f i nal i nt SI ZE;s t at i c{
SI ZE = 123;}
}publ i c cl ass Const ant s
{ pr ot ected f i nal i nt SI ZE;{
SI ZE = 123; / / compi l er er r or}
}
Polymorphism
Polymorphism. Poly means many and morph means form. Thus,
polymorphism refers to being able to use many forms of a type without regardto the details.
-
8/12/2019 Learn Java in 30 Days Free
43/184
UIU Lecture 2b, CSI 211 9/11
Example using Interface
import j ava. ut i l . Random;
class Shape {
void dr aw( ) {}
void er ase( ) {}
}
class Ci r cl e extends Shape {void dr aw( ) {
Syst em. out . pr i nt l n( "Ci r c l e. dr aw( ) " ) ;}
void er ase( ) {Syst em. out . pr i nt l n( "Ci r cl e. er ase( ) " ) ;
}}
class Squar e extends Shape {void dr aw( ) {
Syst em. out . pr i nt l n( " Square. dr aw( ) " ) ;}
void er ase( ) {Syst em. out . pr i nt l n( "Squar e. er ase( ) " ) ;
}}
class Tr i angl e extends Shape {void dr aw( ) {Syst em. out . pr i nt l n( "Tri angl e. dr aw( ) " ) ;
}
void er ase( ) {Syst em. out . pr i nt l n( "Tri angl e. er ase( ) " ) ;
}}
/ / A " f act ory" t hat r andoml y cr eat es shapes:
class RandomShapeGener at or { private Random r and = new Random( ) ;
public Shape next ( ) {switch ( r and. next I nt ( 3) ) {default :case 0:
return new Ci r cl e( ) ;case 1:
return new Squar e( ) ;case 2:
-
8/12/2019 Learn Java in 30 Days Free
44/184
-
8/12/2019 Learn Java in 30 Days Free
45/184
UIU Lecture 2b, CSI 211 11/11
publ i c cl ass Cat ext ends Ani mal{
publ i c Dog( St r i ng nm){
super ( nm) ; / / bui l ds par ent}publ i c voi d speak( ) / / t hi s met hod speci f i c t o ani mal{
Syst em. out . pr i nt l n( "Cat speaks") ;}
}
publ i c cl ass Ani mal Ref erence{
publ i c s tat i c voi d mai n( St r i ng ar gs[ ] )Ani mal r ef / / set up var f or an Ani malCat aCat = new Cat ( " Bossy" ) ; / / makes speci f i c obj ect sDog aDog = new Dog( " Rover " ) ;
/ / now r ef er ence each as an Ani mal
r ef = aCat ; r ef . speak() ;r ef = aDog; r ef . speak( ) ;}
*************** End of Lecture 2b **************
-
8/12/2019 Learn Java in 30 Days Free
46/184
UIU Lecture 3a, CSI 211 1/8
United International University
Course: CSI 211 Course Title: Object Oriented Programming
Lecture 3a: Object oriented concept, Information hiding; examples.
Objects and Constant Variables
When an object reference is final, as is "object" below, the reference can be
assigned only once. The state of the object can change. This is shown below
where the state of "object" is legally changed by directly accessing the field and
using a method. However, assigning a new reference to the variable "object" is
not allowed.
publ i c cl ass Test{publ i c s t at i c voi d mai n( St r i ng ar gs[ ] )
{f i nal Sampl e obj ect = new Sampl e( ) ;obj ect . dat a = 5; / / OKobj ect . set Dat a( 12 ) ; / / OKobj ect = new Sampl e( ) ; / / Compi l e Er r or}
}publ i c cl ass Sampl e
{publ i c i nt dat a = 3;
publ i c voi d set Dat a( i nt newVal ue ){dat a = newVal ue;}
}
Initialization Order
A class is initialized when it is first "actively" used, i.e.o A method defined in the class is invoked
o A constructor in the class is invoked
o A non-constant field in the class is accessed A class is initialized by performing direct assignments of static fields and static
initialization blocks are done in order from top to bottom of the class
-
8/12/2019 Learn Java in 30 Days Free
47/184
UIU Lecture 3a, CSI 211 2/8
When an object is created, after the class in initialized, all instance field are
initialized by:
o performing direct assignments of non-static fields and instance
initialization blocks are done in order from top to bottom of the class,
then the constructor is executed
When you initialize a field you can not make a forward reference another field
publ i c cl ass For war dRef er enceAndI ni t i al i zat i on{
publ i c s t at i c i nt f i r s t = 1;publ i c s t at i c i nt second = f i r s t * 2;publ i c s t at i c i nt t hi r d = f our t h - 1; / / Compi l er er r orpubl i c st at i c i nt f our t h = 4;publ i c i nt f i f t h = 5;publ i c i nt s i xt h = f i f t h + 1;publ i c i nt sevent h = ei ght h - 1; / / Compi l er er r orpubl i c i nt ei ght h = 8;
}
When initializing a field you can make a forward reference to a method
publ i c cl ass For war dRef erenceAndFunct i ons{
publ i c i nt f i f t h = get Si xt h( ) ;publ i c i nt s i xt h = f i f t h + 1;publ i c i nt sevent h = get Si xt h( ) ;publ i c i nt get Si xt h( ){
re turn si xt h;}
}
publ i c cl ass Test{
publ i c st at i c voi d mai n( St r i ng[ ] ar gument s ){
For war dRef er enceAndFunct i ons wor ks;wor ks = new For war dRef er enceAndFunct i ons( ) ;Sys tem. out . pr i nt l n( " f i f t h " + works . f i f t h ) ;Syst em. out . pr i nt l n( "si xt h " + wor ks. s i xt h ) ;System. out . pr i nt l n( "sevent h " + works. sevent h );}
}Outputf i f t h 0si xt h 1
-
8/12/2019 Learn Java in 30 Days Free
48/184
UIU Lecture 3a, CSI 211 3/8
sevent h 1
Recursion
It is the process of a method calling itself. A recursion has two parts
stop condition call itself
Recursion is an expensive procedure and it is better to avoid recursion if you do not need
package l ect ur e02b;
public class MyMat hLi br ar y {
public static int f act or i al ( int n) {
if ( n
-
8/12/2019 Learn Java in 30 Days Free
49/184
-
8/12/2019 Learn Java in 30 Days Free
50/184
UIU Lecture 3a, CSI 211 5/8
Using the Stack..
St ack me = new St ack( 20 ) ;me. push( 5 ) ;me. push( 12 ) ;Syst em. out . pr i nt l n( me. pop( ) ) ;
Syst em. out . pr i nt l n( me. pop( ) ) ;. .
A Struct Version - C Programming
st r uct St ack{
f l oat s t ack[ 100] ;i nt t opOf St ack;
};voi d push( St ack& i t , i nt i t em){
i t . st ack[ ( i t . t opOf St ack) ++] = i t em;}f l oat pop( St ack& i t ){
r et ur n i t . s t ack[ - - ( i t . t opOf St ack) ] ;}mai n( ){
St ack t r yThi sOut ;St ack your s, mi ne;t r yThi sOut . t opOf St ack = 0; / / i nf or mat i on i s not hi dden!your s. t opOf St ack = 0;push( t r yThi sOut , 5. 0 ) ;
push( your s, 3. 3 ) ;push( t r yThi sOut , 9. 9 ) ;cout
-
8/12/2019 Learn Java in 30 Days Free
51/184
UIU Lecture 3a, CSI 211 6/8
Some Typical Beginners
Mistake #1
Struct-like Class
One can make a class that is just a struct dressed as a class. Avoid this doing this.
cl ass St ackDat a{
publ i c f l oat [ ] el ement s = new f l oat [ 100] ;publ i c i nt t opOf St ack = 0;
}
cl ass Test{
st at i c voi d push( St ack i t , i nt i t em){
i t . st ack[ ( i t . t opOf St ack ) ++ ] = i t em;}s ta t i c f l oat pop( St ack i t ){
r et ur n i t . s t ack[ - - ( i t . t opOf St ack) ] ;}publ i c voi d s t at i c mai n( St r i ng[ ] ar gs){
St ack your s, mi ne;push( your s, 3. 3 ) ;push( mi ne, 9. 9) ;
}
}
Mistake #2
This example has all fields hidden. But the methods do not support the stack abstraction.The logic of operating the stack is not in the stack class. This means that the topOfStackfield can be improperly set by some one outside the class.
cl ass St ackDat a{
pr i vat e f l oat [ ] el ement s = new f l oat [ 100] ;pr i vat e i nt t opOf St ack = - 1;
publ i c i nt get TopOf St ack( ){r et ur n t opOf St ack;
}publ i c voi d set TopOf St ack( i nt newTop ){
t opOf St ack = newTop;}
-
8/12/2019 Learn Java in 30 Days Free
52/184
UIU Lecture 3a, CSI 211 7/8
publ i c f l oat get El ement ( i nt el ement I ndex ){
r et ur n el ement s[ el ement I ndex ] ;}publ i c voi d set El ement ( i nt el ement I ndex, f l oat el ement ){
el ement s[ el ement I ndex ] = el ement ;}
}
Mistake #3
Adding IO to the push and pop methods make the stack class unusable. This oftenhappens in new student programs.
cl ass St ack {
pr i vat e f l oat [ ] el ement s = new f l oat [ 100 ] ;pr i vat e i nt t opOf St ack = - 1;
publ i c voi d push( ){
f l oat i t em = Consol e. r eadFl oat ( "Type a f l oat t o push") ;el ement s[ ++t opOf St ack ] = i t em;
}
publ i c voi d pop( ){
Consol e. pr i nt l n( "Top st ack i t em: " +el ement s[ t opOf St ack- - ] ;
}}
cl ass Test{
publ i c voi d s t at i c mai n( St r i ng[ ] ar gs){
St ack your s ohNo = new St ack( ) ;ohNo. push( ) ;ohNo. push( ) ;ohNo. pop( ) ;
}
-
8/12/2019 Learn Java in 30 Days Free
53/184
UIU Lecture 3a, CSI 211 8/8
Design Heuristics
All data should be hidden within its class A class should capture one and only one key abstraction - do not mix many
classes in one class. Keep related data and behavior in one place Beware of classes that have many accessor methods in their public interface.
This implies data and behavior are not in one place
Applying these heuristics to your classes will go a long way to help you avoid typical
beginner mistakes in designing classes
*************** End of Lecture 3a **************
-
8/12/2019 Learn Java in 30 Days Free
54/184
UIU Lecture 3b, CSI 211 1/11
United International University
Course: CSI 211 Course Title: Object Oriented Programming
Lecture 3b: Inheritance and Class relationships.
Inheritance
inheritance is a way to form new classes (instances of which are called objects)
using classes that have already been defined.
The new classes, known as derived classes, take over (or inherit) attributes and
behavior of the pre-existing classes, which are referred to as base classes (or
ancestor classes).It is intended to help reuse existing code with little or no modification.
cl ass Par ent {publ i c i nt par ent Var i abl e = 10;publ i c voi d par ent Funct i on( ) {
Syst em. out . pr i nt l n( "Par ent Funct i on" ) ;}
}cl ass Chi l d ext ends Par ent {
publ i c voi d chi l dFunct i on( ) {par ent Funct i on( ) ;Syst em. out . pr i nt l n( "I n Chi l d " + par ent Var i abl e ) ;
}}cl ass I nher i t ance {
publ i c s t at i c voi d mai n( St r i ng ar gs[ ] ) {
Chi l d exampl e = new Chi l d( ) ;exampl e. chi l dFunct i on( ) ;exampl e. par ent Funct i on( ) ;Syst em. out . pr i nt l n( exampl e. par ent Var i abl e ) ;
}}
OutputPar ent Funct i onI n Chi l d 10Par ent Funct i on10
Inheritance
-
8/12/2019 Learn Java in 30 Days Free
55/184
UIU Lecture 3b, CSI 211 2/11
A class can be extended or subclassed
The class that is extended is a superclass
Some people use the words parent class or base class to mean a superclass
The extended class is a subclass or extended class of its superclass
Some people use the word child class to mean subclass
An object created from the subclass has its own copy of all the nonstatic fields
defined in its superclass
Java does not support multiple inheritance
Class Object
All classes inherit directly or indirectly from java.lang.Object
- class Parent { int size; }- class Parent extends Object { int size; }
The child class below is a grandchild of Object
- Having a common ancestor class allows java to provide standards on all objects, liketoString()
cl ass Par ent { i nt s i ze; }cl ass Chi l d ext ends Par ent { i nt age; }cl ass Test Obj ect {
publ i c s t at i c voi d mai n( St r i ng ar gs[ ] ) {Par ent wat chThi s = new Par ent ( ) ;i nt myHash = wat chThi s. hashCode( ) ;Syst em. out . pr i nt l n( myHash ) ;
/ / Wher e does hashCode come f r om?}
}
-
8/12/2019 Learn Java in 30 Days Free
56/184
UIU Lecture 3b, CSI 211 3/11
Some Object's Methods
clone() - Creates a clone of the object.
equals(Object) - Compares two Objects for equality.
Uses "==" to test for equality
toString() - Returns a String that represents the value of this Object.
If a class needs an implementation of equals, which differs from the default
"equals", the class should override both equals and hashCode
If two different objects satisfy the equals method, the hashCode should return thesame value for both objects
Casting and ClassesAn instance of a child class can be assigned to a variable (field) of the parent
class.
If a variable references an object of a subclass, the object can be cast down to its
actual type with an explicit cast. The explicit cast is required. A runtime error
occurs when explicitly casting an object to a type that it is not.
In the code below the cast "(Uncle) object" is a runtime error because at that time
object holds an instance of the Child class, which is not of type (or subclass) of
Uncle. An object of type Parent cannot be cast to type Child.
cl ass Par ent { i nt dat a; }cl ass Chi l d ext ends Par ent { St r i ng name; }cl ass Uncl e { St r i ng r i ch; }cl ass Cast i ng {
publ i c s t at i c voi d mai n( Str i ng ar gs[ ] ) {Obj ect obj ect ;Par ent par ent ;Chi l d chi l d = new Chi l d( ) ;
-
8/12/2019 Learn Java in 30 Days Free
57/184
UIU Lecture 3b, CSI 211 4/11
Uncl e uncl e;par ent = chi l d;obj ect = chi l d;par ent = ( Par ent ) obj ect ; / / expl i ci t cast downchi l d = ( Chi l d) obj ect ; / / expl i ci t cast downuncl e = ( Uncl e) obj ect ; / / Runt i me except i on}
}
Output j ava. l ang. Cl assCast Except i on: Chi l d: cannot cast t o Uncl e
Inheritance and Name Clashes
What happens when the parent class has a method(field) with the same name as a
method(field) of the child class?
Terms and Rules
Overloading
Providing more than one method with the same name, but with different signatures
Overriding
A class replacing an ancestor's implementation of a method with an implementation of it
own Signature and return type must be the same .
Static methods can not be overridden
Overriding Methods Note that the statement "overRidden.print();" prints out different text depending on whattype of object overRidden references.
cl ass Par ent {
publ i c voi d pr i nt ( ) {Syst em. out . pr i nt l n( "I n Par ent " ) ;}
}cl ass Chi l d ext ends Par ent {
publ i c voi d pr i nt ( ) {Sys tem. out . pr i nt l n( " I n Chi l d" ) ;
}}cl ass Over r i ddi ngMet hods {
-
8/12/2019 Learn Java in 30 Days Free
58/184
UIU Lecture 3b, CSI 211 5/11
publ i c s t at i c voi d mai n( St r i ng ar gs[ ] ) {Chi l d whoAmI = new Chi l d( ) ;whoAmI . pr i nt ( ) ;Par ent over Ri dden = whoAmI ;over Ri dden. pr i nt ( ) ;over Ri dden = new Par ent ( ) ;over Ri dden. pr i nt ( ) ;
}}
OutputI n Chi l dI n Chi l dI n Par ent
Overriding and Return TypesWhen overriding a method, the child's method must have the same signature and
return type as the parent's method.cl ass Par ent {
publ i c voi d pr i nt ( ) {Syst em. out . pr i nt l n( "I n Par ent " ) ;
}
publ i c voi d pr i nt ( St r i ng message ) {Syst em. out . pr i nt l n( "I n Par ent " + ' \ t ' + message ) ;
}publ i c voi d pr i nt ( i nt val ue ) {
Syst em. out . pr i nt l n( "I n Par ent " + ' \ t ' + val ue ) ;}
}cl ass Chi l d ext ends Par ent {
publ i c i nt pr i nt ( ) { / / Compi l er Er rorSys tem. out . pr i nt l n( " I n Chi l d" ) ;r et ur n 5;
}publ i c voi d pr i nt ( St r i ng message ) {
Syst em. out . pr i nt l n( "I n Chi l d" + ' \ t ' + message ) ;}
}cl ass Ret urnTypesCount {
publ i c s t at i c voi d mai n( St r i ng ar gs[ ] ) {Chi l d whoAmI = new Chi l d( ) ;whoAmI . pr i nt ( ) ;
whoAmI . pri nt ( " Hi Mom" ) ;whoAmI . pr i nt ( 10 ) ; / / Ok i n J ava,
/ / Compi l e er r or i n C++}
}
-
8/12/2019 Learn Java in 30 Days Free
59/184
UIU Lecture 3b, CSI 211 6/11
Super
Refers to the superclass of class that implements the method containing thereference to superAll references to super are resolved statically
To find out what class super refers to go to the source code, find the code that contains"super", then go to that classes parent class.
cl ass Par ent { St r i ng name = " Par ent " ; }cl ass Chi l d ext ends Par ent {
St r i ng name = " Chi l d" ;publ i c voi d pr i nt ( ) {
Syst em. out . pr i nt l n( name );Syst em. out . pr i nt l n( super . name );
}}cl ass Gr andChi l d ext end Chi l d {
St r i ng name = " Gr andChi l d";}cl ass Super Mai n {
publ i c s t at i c voi d mai n( St r i ng ar gs[ ] ) {Gr andChi l d whoAmI = new Gr andChi l d( ) ;whoAmI . pr i nt ( ) ;
}}OutputChi l dPar ent
super.super
- J ava does not al l ow you t o chai n supers t o r ef er t o your gr andpar entcl ass
- super . super i s not al l owed i n J ava
Constructors and Inheritance
Before the constructor in a Child class is called, its parent's constructor will be called
a) Implicit Call to Parent's Constructor
cl ass Par ent {publ i c Par ent ( ) {
Sys tem. out . pr i nt l n( " \ t I n Parent " ) ;}
}
-
8/12/2019 Learn Java in 30 Days Free
60/184
UIU Lecture 3b, CSI 211 7/11
cl ass Chi l d ext ends Par ent {publ i c Chi l d( ) {
Sys tem. out . pr i nt l n( " \ t I n Chi l d" ) ;}publ i c Chi l d( St r i ng not Used ) {
Syst em. out . pr i nt l n( "\ t I n Chi l d wi t h ar gument " ) ;}
}cl ass Const r uct or s {
publ i c s t at i c voi d mai n( St r i ng ar gs[ ] ) {Syst em. out . pr i nt l n( "Const r uct Par ent " ) ;Par ent sl eepy = new Par ent ( ) ;Syst em. out . pr i nt l n( "Const r uct Chi l d" ) ;Chi l d car e = new Chi l d( ) ;Syst em. out . pr i nt l n( "Const r uct Second Chi l d" ) ;car e = new Chi l d( "Tr y Me" ) ;
}}
OutputConst r uct Par ent
I n Par entConst r uct Chi l d
I n Par entI n Chi l d
Const r uct Second Chi l dI n Par entI n Chi l d wi t h ar gument
b) Explicit Call to Parent's Constructors
cl ass Par ent {publ i c Par ent ( ) {
Syst em. out . pr i nt l n( " I n Par ent , No Ar gument " ) ;}publ i c Par ent ( St r i ng message ) {
Syst em. out . pr i nt l n( " I n Par ent " + message ) ;}
}cl ass Chi l d ext ends Par ent {
publ i c Chi l d( St r i ng message, i nt val ue ) {t hi s( message ) ; / / i f occur s must be
f i r s t
Sys tem. out . pr i nt l n( " I n Chi l d" ) ;}publ i c Chi l d( St r i ng message ) {
super ( message ) ; / / i f occur s must be f i r stSyst em. out . pr i nt l n( " I n Chi l d" + message ) ;
}}cl ass Const r uct or s {
publ i c s t at i c voi d mai n( St r i ng ar gs[ ] ) {Syst em. out . pr i nt l n( "Const r uct Chi l d" ) ;
-
8/12/2019 Learn Java in 30 Days Free
61/184
-
8/12/2019 Learn Java in 30 Days Free
62/184
-
8/12/2019 Learn Java in 30 Days Free
63/184
UIU Lecture 3b, CSI 211 10/11
publ i c voi d Sampl eAccess( Bot any. Pr ot ect ed noAccess) {noAccess. name = " Thi s i s a compi l e Er r or " ;
}}package Tr ee;publ i c cl ass Chi l d ext ends Bot any. Pr ot ect ed {
publ i c voi d Sampl eAccess( Bot any. Pr ot ect ed noAccess,Chi l d accessOK) {
name = "Thi s i s l egal , I am r el at ed";noAccess. name = " Thi s i s a compi l e Er r or " ;accessOK. name = "Thi s i s l egal " ;
}}
Package Access
Accessible in the package that contains the class Not accessible outside the package that contains the class
package Bot any;publ i c cl ass NoExpl i ci t {
St r i ng name = " No expl i ci t access l evel gi ven" ;}package Bot any;publ i c cl ass NoRel at i on {
publ i c voi d Sampl eAccess( NoExpl i ci t accessOK ) {accessOK. name = "Thi s i s l egal " ;
}}
package Tr ee;publ i c cl ass NoRel at i onEi t her {publ i c voi d Sampl eAccess( Bot any. NoExpl i ci t noAccess) {
noAccess. name = " Thi s i s a compi l e Er r or " ;}
}package Tr ee;publ i c cl ass Chi l d ext ends Bot any. NoExpl i ci t {
publ i c voi d Sampl eAccess( Bot any. NoExpl i ci t noAccess,Chi l d al soNoAccess) {
name = " I am r el at ed, but t hi s i s NOT LEGAL" ;noAccess. name = " Thi s i s a compi l e Er r or " ;al soNoAccess. name = " Thi s i s a compi l e Er r or " ;
}}
Public AccessAccessible by any one
}
-
8/12/2019 Learn Java in 30 Days Free
64/184
UIU Lecture 3b, CSI 211 11/11
*************** End of Lecture 3a **************
-
8/12/2019 Learn Java in 30 Days Free
65/184
UIU Lecture 4a, CSI 211 1/12
United International University
Course: CSI 211 Course Title: Object Oriented Programming
Lecture 3a: Interfaces.
Final
The final modifier provides:
SecurityPerformance optimizationsA class declared final, can not have any subclasses
f i nal cl ass EndOf TheLi ne {i nt noSubcl assPossi bl e;publ i c voi d aFunct i on( ) {
Syst em. out . pr i nt l n( " Hi Mom" ) ;}
}
cl ass Thi sWi l l Not Wor k ext ends EndOf TheLi ne {i nt ohNo;
}Does not compile
Final MethodA final method can not be overridden
cl ass Par ent {publ i c f i nal voi d t heEnd( ) {
Sys t em. out . pr i nt l n( "Thi s i s i t " ) ;}publ i c voi d normal ( ) {
Syst em. out . pr i nt l n( "I n par ent " ) ;}
}cl ass Chi l d ext ends Par ent {
publ i c voi d t heEnd( ) { / / Compi l e Er r orSyst em. out . pr i nt l n( " Two Ends?" ) ;
}publ i c voi d normal ( ) {
Sys tem. out . pr i nt l n( " I n Chi l d" ) ;}
}
Abstract class and abstract Method
-
8/12/2019 Learn Java in 30 Days Free
66/184
UIU Lecture 4a, CSI 211 2/12
An abstract class is a class that is declared abst r act it may or may not include
abstract methods.
o Abstract classes cannot be instantiated, but they can be subclassed.
o When an abstract class is subclassed, the subclass usually providesimplementations for all of the abstract methods in its parent class.
o if it does not, the subclass must also be declared abst r act
An abstract method is a method that is declared without an implementation
(without braces, and followed by a semicolon), like this:
abst r act cl ass NoObj ect s {i nt noDi r ect Obj ect Possi bl e = 5;publ i c voi d aFunct i on( ) {
Syst em. out . pr i nt l n( " Hi Mom" ) ;}publ i c abst r act voi d subCl assMust I mpl ement ( i nt f oo ) ;
}cl ass Concr et e ext ends NoObj ect s {
publ i c voi d subCl assMust I mpl ement ( i nt f oo ) {Syst em. out . pr i nt l n( "I n Concret e" ) ;
}}cl ass Abst r act Cl asses {
publ i c s tat i c voi d mai n( St r i ng ar gs[ ] ) {NoObj ect s usef ul = new Concr et e( ) ;Concr et e t hi sWor ks = new Concr et e( ) ;usef ul . subCl assMust I mpl ement ( 10 ) ;
Syst em. out . pr i nt l n( t hi sWor ks. noDi r ect Obj ect Possi bl e ) ;}
}OutputI n Concr et e
Relationships between Classes
Is-kind-of / is-a / is-a-type-ofis-analogous-tois-part-of or has-a
a) Is-kind-of, is-a, is-a-type-of
-
8/12/2019 Learn Java in 30 Days Free
67/184
UIU Lecture 4a, CSI 211 3/12
Let A and B be classes
To determine if A should be the parent class of B ask:
Is B an A ( or is B a type of A, or is B a kind of A)
If the answer is yes, then B is in is-a relationship to A
Example# 1 - Bank Accounts
A J uni or Savi ngsAccount i s a t ype of a Savi ngsAccount
So, consi der maki ng J uni or Savi ngsAccount a subcl ass of Savi ngsAccount
Example# 2 - Employees
Consi der Empl oyee, Manager , Engi neer , and Fi l eCl er k
A Manager i s a ki nd of an Empl oyee.
cl ass Empl oyee{/ / st uf f not shown}
cl ass Manager ext ends Empl oyee{
/ / st uf f not shown}
-
8/12/2019 Learn Java in 30 Days Free
68/184
UIU Lecture 4a, CSI 211 4/12
b) is-analogous-to
If class X is-analogous-to class Y then look for superclass
Example BankAccounts
A checking account is analogous to a saving account
c) is-part-of or has-a
If class A is-part-of class B then there is no inheritance
Some negotiation between A and B for responsibilities may be needed
Example: Linked-List class and a Stack
A stack uses a linked-list in its implementation
A stack has a linked-list
The Stack class and the LinkedList class are separate classes
-
8/12/2019 Learn Java in 30 Days Free
69/184
UIU Lecture 4a, CSI 211 5/12
cl ass Li nkedLi st{publ i c voi d addFr ont ( Obj ect i t em) { / / not shown}publ i c Obj ect r emoveFr ont ( ) { / / not shown}publ i c Obj ect r emoveEnd( ) { / / not shown}}
cl ass St ack{Li nkedLi st st ackEl ement s = new Li nkedLi st ( ) ;publ i c voi d push( Obj ect i t em )
{st ackEl ement s. addFr ont ( i t em) ;}
}
Interfaces
Let B & C be classes. Assume that we make A the parent class of B and C so A can hold
the methods and fields that are common between B and C.
Sometimes a method in B is so different from the same method in C there is no shared
implementation possible in A. We can make the method and A an abstract classes. The
methods in A then indicate which methods must be implemented in B and C. A can act as
type, which can hold objects of type B or C.
Sometimes all the methods of B must be implemented differently than the same method
in C. Make A an interface.
-
8/12/2019 Learn Java in 30 Days Free
70/184
UIU Lecture 4a, CSI 211 6/12
Interfaces can specify public methods but can have no implementation of
methods.
Thus, one can not make an object from an interface.
Interfaces can have fields. All fields in an interface are final and static even if
they are not explicitly declared as such.
Interfaces have the same access levels as classes, public and package.
A class can implement more that one interface. If a parent class implements an
interface, its child classes automatically implement the interface.
An interface, like a class, defines a type. Fields, variables, and parameters can be
declared to be of a type defined by an interface.
Interface ExampleThis example shows the syntax of declaring an interface and a class implementing theinterface. The class must either implement all the methods in the interface or be anabstract class.
a) Implementing all methods
publ i c i nt er f ace Door {publ i c voi d open( ) ;publ i c voi d c l ose( ) ;
}publ i c cl ass Car Door i mpl ement s Door {
publ i c voi d open( ) {Syst em. out . pr i nt l n( "Ent er t he car " ) ;
}publ i c voi d cl ose( ) {
Syst em. out . pr i nt l n( "Look out , cl osi ng t he door ") ;}
}cl ass Test Door {
publ i c s tat i c voi d mai n( St r i ng[ ] ar gs ) {Door aut omat i c = new Car Door ( ) ;
aut omat i c. open( ) ;Car Door di r ect = new Car Door ( ) ;di r ec t . open( ) ;
}}
OutputEnt er t he carEnt er t he car
-
8/12/2019 Learn Java in 30 Days Free
71/184
UIU Lecture 4a, CSI 211 7/12
b) Abstract Class implementation of Interface
This example shows a class that implements only some of the methods declared in aninterface. The class "CarDoor" must then be declared abstract. Objects can not be createdof the "CarDoor" class. A subclass must implement the missing method.
publ i c i nt er f ace Door {publ i c voi d open( ) ;publ i c voi d c l ose( ) ;
}abst r act cl ass Car Door i mpl ement s Door {
publ i c voi d open( ) {Syst em. out . pr i nt l n( "Ent er t he car " ) ;
}}
All Interface Methods are Public
It is a compile error to declare a method as private or protected in an interface. Anymethod without an access level in an interface is a public method. This can be confusingso always declare methods in an interface as public.
Example # 1
publ i c i nt er f ace BadAccess {publ i c voi d A( ) ;
pr ot ect ed voi d B( ) ; / / compi l e er r orvoi d C( ) ; / / l ooks l i ke package, but i s publ i cpr i vat e voi d D( ) ; / / compi l e er r or
}
Example# 2package whi t ney;publ i c i nt er f ace GoodAccess {
publ i c voi d A( ) ;voi d C( ) ;
}package t est ;i mpor t whi t ney. GoodAccess;cl ass BadI mpl ement at i on i mpl ement s GoodAccess {
publ i c voi d A( ) {}voi d C( ) {} / / Compi l e er r or, wr ong access l evel
}cl ass GoodI mpl ement at i on i mpl ement s GoodAccess {
publ i c voi d A( ) {}publ i c voi d C( ) {}
}
-
8/12/2019 Learn Java in 30 Days Free
72/184
UIU Lecture 4a, CSI 211 8/12
Interfaces and Static Fields
Fields can be declared in an interface.
o All fields are public static and final.
o Declaring a field to be any other access level except public is a compileerror.
o If no access level is given, it defaults to public.
o If a field is not explicitly declared to be static or final, the field is stillstatic and final.
You may be tempted to use interfaces as a place to put program constants. Avoidthis. Usually a constant belongs to some abstraction. This abstraction should berepresented by a class. Place the constant in that class.
i nt er f ace Wi t hSt at i c {publ i c s tat i c f i nal i nt EXPLI CI T = 42;publ i c st at i c i nt I S_FI NAL = 12;publ i c i nt I S_FI NAL_AND_STATI C = 3;pr ot ect ed i nt COMPI LE_ERROR = 4;
publ i c i nt NO_VALUE_COMPI LE_ERROR;}cl ass Radi o i mpl ement s Wi t hSt at i c {
publ i c voi d AM( ) {Syst em. out . pr i nt l n( I S_FI NAL ) ;
}
}cl ass Test {publ i c s tat i c voi d mai n( St r i ng ar gs[ ] ) {
Syst em. out . pr i nt l n( Wi t hSt at i c . EXPLI CI T ) ;Syst em. out . pr i nt l n( Radi o. EXPLI CI T ) ;Radi o megaBass = new Radi o( ) ;Syst em. out . pr i nt l n( megaBass. EXPLI CI T ) ;megaBass. AM( ) ;
}}
-
8/12/2019 Learn Java in 30 Days Free
73/184
UIU Lecture 4a, CSI 211 9/12
Extending Interfaces
One interface can inherit from another interface. Interfaces support multiple inheritance.
i nt er f ace Door {publ i c voi d open( ) ;publ i c voi d c l ose( ) ;
}i nt er f ace Lockabl eDoor ext ends Door {
publ i c voi d l ock( ) ;publ i c voi d unl ock( ) ;
}cl ass Car Door i mpl ement s Lockabl eDoor {
pr i vat e bool ean i sLocked = f al se;publ i c voi d open( ) {
i f ( ! i sLocked)Syst em. out . pr i nt l n( "Ent er t he car " ) ;
}publ i c voi d cl ose( ) {
Syst em. out . pr i nt l n( "Look out , cl osi ng t he door ") ;}
publ i c voi d l ock() { i sLocked = t r ue; }publ i c voi d unl ock( ) { i sLocked = f al se; }
}cl ass Test Door {
publ i c s tat i c voi d mai n( St r i ng[ ] ar gs ) {Door aut omat i c = new Car Door ( ) ;aut omat i c. open( ) ;aut omat i c . l ock( ) ; / / Compi l e er r orLockabl eDoor bet t er = ( Lockabl eDoor ) aut omat i c;bet t er. l ock( ) ; / / OK
}}
-
8/12/2019 Learn Java in 30 Days Free
74/184
-
8/12/2019 Learn Java in 30 Days Free
75/184
-
8/12/2019 Learn Java in 30 Days Free
76/184
UIU Lecture 4a, CSI 211 12/12
Abstract Class vs Interface
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abst r act voi d moveTo( doubl e del t aX, doubl e del t aY) ;
If a class includes abstract methods, the class itself must be declared abst r act , as in:publ i c abst r act cl ass Gr aphi cObj ect {
/ / decl ar e f i el ds/ / decl ar e non- abst r act met hodsabst r act voi d dr aw( ) ;
}
We can not make i nst ance of Abst r act Cl ass as wel l as I nt er f ace.
Choosi ng i nt er f aces and abst r act cl asses i s not an ei t her / or
pr oposi t i on. I f you need t o change your desi gn, make i t an
i nt er f ace. However , you may have abst r act cl asses t hat pr ovi de
some def aul t behavi or. Abst r act cl asses ar e excel l ent candi dat es
i nsi de of appl i cat i on f r amewor ks.
i nt er f ace cont ai ns met hods t hat must be abst r act ; abst r act cl ass
may cont ai n concr et e met hods.
i nt er f ace cont ai ns var i abl es t hat must be st at i c and f i nal ;
abst r act cl ass may cont ai n non- f i nal and f i nal var i abl es.
member s i n an i nt er f ace ar e publ i c by def aul t , abst r act cl ass
may cont ai n non- publ i c member s.
i nt er f ace i s used t o "i mpl ement s"; wher eas abst r act cl ass i s
used t o "ext ends" .
i nt er f ace can be used t o achi eve mul t i pl e i nher i t ance; abst r act
cl ass can be used as a si ngl e i nher i t ance.
i nt er f ace can "ext ends" another i nt er f ace, abst r act cl ass can
" ext ends" anot her cl ass and " i mpl ement s" mul t i pl e i nt er f aces.
i nt er f ace i s absol ut el y abst r act ; abst r act cl ass can be i nvoked
i f a mai n( ) exi s t s .
i nt er f ace i s mor e f l exi bl e t han abst r act cl ass because one cl ass
can onl y "ext ends" one super cl ass, but " i mpl ement s" mul t i pl e
i nt er f aces .
I f gi ven a choi ce, use i nt er f ace i nst ead of abst r act cl ass.
*************** End of Lecture 4a **************
-
8/12/2019 Learn Java in 30 Days Free
77/184
-
8/12/2019 Learn Java in 30 Days Free
78/184
UIU Lecture 3b, CSI 211 2/9
Using the Default Clone Process
This example shows the minimum effort needed to support the clone method. We willcover exceptions (the throws CloneNotSupportedException) in later lectures.
publ i c cl ass Sampl e i mpl ement s Cl oneabl e {pr i vat e i nt s i ze = 0;
publ i c voi d set Si ze( i nt newSi ze ) { si ze = newSi ze; }
publ i c St r i ng t oSt r i ng( ) {r et ur n "Si ze: " + s i ze;
}
publ i c Obj ect cl one( ) t hr ows Cl oneNot Support edExcept i on {r et ur n super . cl one( ) ;
}
}publ i c cl ass Test {publ i c s tat i c voi d mai n( St r i ng ar gs[ ] )
t hrows Cl oneNot Suppor t edExcept i on {Sampl e a = new Sampl e( ) ;Sampl e b = ( Sampl e) a. cl one( ) ;a. set Si ze( 12 ) ;Syst em. out . pr i nt l n( "a " + a ) ;Syst em. out . pr i nt l n( "b " + b ) ;
}}Outputa Si ze: 12b Si ze: 0
clone() is not "new"
This example demonstrates that when you clone an object constructors and initialization block are not called. While not shown here, direct assignments in fields are also not donewhen cloning objects as they are done when you create an object via "new".
publ i c cl ass Cl oneI sNot New i mpl ement s Cl oneabl e {{
Sys tem. out . pr i nt l n( " I n i ns tance i ni t i al i zat i on bl ock") ;}
publ i c Cl oneI sNot New( ) {Syst em. out . pr i nt l n( " I n const r uctor" ) ;
}
publ i c Obj ect cl one( ) {r et ur n super . cl one( ) ;
}
-
8/12/2019 Learn Java in 30 Days Free
79/184
UIU Lecture 3b, CSI 211 3/9
}publ i c cl ass Test {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows Except i on {Cl oneI sNot New a = new Cl oneI sNot New( ) ;Syst em. out . pr i nt l n( " St ar t c l one") ;Cl oneI sNot New b = ( Cl oneI sNot New) a. cl one( ) ;Cl oneI sNot New c = ( Cl oneI sNot New) a. cl one( ) ;
}}
OutputI n i ns tance i ni t i al i zat i on bl ockI n const r uct orSt ar t cl one
Problems with Default clone()
The default clone method clones the reference but not object or array that is referenced
Using the default clone on an object with a field that is a reference results in two objectswith references to the same item. Let Wrapper be a class that has a field, which is areference to another object. For this example, the other object as a field of type int. Usingthe default clone process we get two wrapper objects, a and b, which both reference thesame object. Any change in the state of this object will be visible through both objects aand b.
Wr apper a = new Wr apper ( ) ;
Wr apper b = ( Wr apper ) a. cl one( ) ;
-
8/12/2019 Learn Java in 30 Days Free
80/184
UIU Lecture 3b, CSI 211 4/9
Using Default clone with Field References
In this example, the class "BadWrapper" has a field that is a reference to a "Sample"object. The class "BadWrapper" uses the default clone process. In class"TestBadWrapper" a "BadWrapper" object is cloned. Now two "BadWrapper" objects
reference the same "Sample" object.
publ i c cl ass Sampl e i mpl ement s Cl oneabl e {pr i vat e i nt s i ze = 0;
publ i c voi d set Si ze( i nt newSi ze ) { si ze = newSi ze; }
publ i c St r i ng t oSt r i ng( ) { r et ur n "Si ze: " + s i ze; }
publ i c Obj ect cl one( ) {r et ur n super . cl one( ) ;
}}
publ i c cl ass BadWr apper i mpl ement s Cl oneabl e {pr i vat e Sampl e aRef er ence =new Sampl e( ) ;
publ i c voi d set Si ze( i nt newSampl eSi ze ) {aRef erence. set Si ze( newSampl eSi ze ) ;
}
publ i c St r i ng t oSt r i ng( ) {r et ur n " Wr apper " + aRef er ence. t oSt r i ng( ) ;
}
publ i c Obj ect cl one( ) {r et ur n super . cl one( ) ;
}}
Note that the state of "a" is changed, but when we print out "a" and "b", they have thesame state. This is because they reference the same "Sample" object.
publ i c cl ass Test BadWr apper{publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows Except i on
{BadWr apper a = new BadWr apper ( ) ;BadWr apper b = ( BadWr apper ) a. cl one( ) ;a. set Si ze( 12 ) ;Syst em. out . pr i nt l n( "a " + a ) ;Syst em. out . pr i nt l n( "b " + b ) ;}
}
Outputa Wr apper Si ze: 12b Wr apper Si ze: 12
-
8/12/2019 Learn Java in 30 Days Free
81/184
-
8/12/2019 Learn Java in 30 Days Free
82/184
UIU Lecture 3b, CSI 211 6/9
Cloning Arrays
If we have an array of basic types, then the array must be cloned if we do not want the
same array referenced in two or more objects. This example shows one way to clone anarray.
publ i c cl ass Ar r ayWr apper i mpl ement s Cl oneabl e {pr i vat e i nt [ ] aRef er ence = { 0 };
publ i c voi d set Si ze( i nt newSampl eSi ze ) {aRef er ence[ 0] = newSampl eSi ze;
}
publ i c St r i ng t oSt r i ng( ) {r et ur n "Wr apper " + aRef er ence[ 0] ; }
publ i c Obj ect cl one( ) t hr ows Cl oneNot Support edExcept i on {
Ar r ayWr apper cl one = ( Ar r ayWr apper ) super . cl one( ) ;cl one. aRef er ence = ( i nt [ ] ) aRef er ence. cl one( ) ;r et ur n cl one;
}}publ i c cl ass Test {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows Except i on {Ar r ayWr apper a = new Ar r ayWr apper ( ) ;Ar r ayWr apper b = ( Ar r ayWr apper) a. cl one( ) ;a. set Si ze( 12 ) ;Syst em. out . pr i nt l n( "a " + a ) ;Syst em. out . pr i nt l n( "b " + b ) ;
}}Outputa Wr apper 12b Wr apper 0
Java Collections
Col l ect i ons ar e obj ect s t hat hol d ot her obj ect s t hat ar e accessed,
pl aced, and mai nt ai ned under some set of r ul es.
Exampl es
Set s
Li st
Map
-
8/12/2019 Learn Java in 30 Days Free
83/184
UIU Lecture 3b, CSI 211 7/9
List
Li st i s an i nt er f ace but The Ar r ayLi st cl ass i s a concret ei mpl ement at i on of Li st i nt er f ace. Thi s cl ass suppor t s dynami c ar r ayst hat can gr ow as needed.
public class Ar ar yLi st Demo {
public static void mai n( St r i ng[ ] ar gs) {
Ar r ayLi st al = new Ar r ayLi s t ( ) ; System. out . pr i nt ( " I ni t i al s i ze of al : " + al . s i z e( ) ) ; System. out . pr i nt ( " \ n" ) ;
/ / add. el ement s t o t he ar r ay l i st al . add( " C" ) ; al . add( " A" ) ;
al . add( " E" ) ; al . add( " B" ) ; al . add( " D" ) ; al . add( " F" ) ; al . add( 1 , " A2" ) ; / / i nser t s obj ect s "A2" i nt o ar r ay at i ndex 1
System. out . pr i nt ( "s i ze of al af t er addi t i ons " + al . s i z e( ) ) ; System. out . pr i nt ( " \ n" ) ;
/ / di spl ay t he ar r ay l i s t System. out . pr i nt ( "cont ent s of al : " + al ) ; System. out . pr i nt ( " \ n" ) ;
/ / Remove el ement s f r om t he ar r ay l i st al . r emove( " F" ) ; al . r emove( 2) ;
System. out . pr i nt ( "s i ze of af t er del et i ons : " + al . s i z e( ) ) ; System. out . pr i nt ( " \ n" ) ; System. out . pr i nt ( "cont ent s of al : " + al ) ;
}
}
Output Screen:
I ni t i al s i ze of al : 0si ze of al af t er addi t i ons 7cont ent s of al : [ C, A2, A, E, B, D, F]s i ze of af t er del et i ons : 5cont ent s of al : [ C, A2, E, B, D]
-
8/12/2019 Learn Java in 30 Days Free
84/184
UIU Lecture 3b, CSI 211 8/9
Iterator
Iterators are used to access the elements of an aggregate object sequentially wi