Top Banner
Java Programming Review (Part I) Enterprise Systems Programming
43

Java Programming Review (Part I) Enterprise Systems Programming.

Dec 24, 2015

Download

Documents

Reginald Green
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java Programming Review (Part I) Enterprise Systems Programming.

Java Programming Review(Part I)

Enterprise Systems Programming

Page 2: Java Programming Review (Part I) Enterprise Systems Programming.

Outline Java programs and packages Classes, fields, methods, objects Naming conventions Types, variables, parameters Arrays Inheritance, interfaces Exceptions Files and streams Static fields and methods Java core packages, collection classes Generics, auto-boxing Inner classes

Page 3: Java Programming Review (Part I) Enterprise Systems Programming.

Java programs A Java program is a collection of classes Each class is specified in a separate file

Source file carries a .java extension Compiled program carries a .class extension

Compilation through the java development kit (JDK) Via the command line: javac ClassName.java

(produces ClassName.class) Through an IDE such as Eclipse or JCreator

Execution requires a Java virtual machine

Page 4: Java Programming Review (Part I) Enterprise Systems Programming.

Java program execution Standalone java programs execute through a run

time environment(the Java VM) Via the command-line: java ClassName Requires ClassName.class ClassName must have a main method

(entry point) but may make use of other java classes Applets and Servlets

Virtual machine resides in browsers or servers Java execution is automatic and triggered by events

Page 5: Java Programming Review (Part I) Enterprise Systems Programming.

Java packages A package is a set of Java classes Packages are Java’s way of organizing its classes

into modules or namespaces Manages complexity and naming conflicts

Classes in a package share increased visibility rules

Packages follow a hierarchical structure and naming pattern e.g., java.awt.event

Classes import classes from outside packages e.g., import java.util.*;

Page 6: Java Programming Review (Part I) Enterprise Systems Programming.

Classes and filenames,packages and folder names The name of a Java class must match the name of

the source file that defines it

This Java source file mustbe named MyClass.java

If it is part of a named package, it should reside in a folder that follows the same hierarchy as its package name

WelcomeServlet.java should reside in a folder named myservlets

public class MyClass{ …}

package myservlets;public class WelcomeServlet{ …}

Page 7: Java Programming Review (Part I) Enterprise Systems Programming.

Class definition in Java

BankAccount Type (or class)

State/attributes (fields)

Behavior (methods)

Code for object creation(usually) done outsideof this class

public class BankAccount{ private double balance = 0;

public double getBalance() { return balance; }

public void deposit( double amount ) { balance = balance + amount; } …}

BankAccount.java

Page 8: Java Programming Review (Part I) Enterprise Systems Programming.

A Class with a constructors

public class BankAccount{ private double balance;

public BankAccount() { balance = 0; } public BankAccount( double initBal ) { balance = initBal; }

public double getBalance() { return balance; } public void deposit( double amount ) { balance = balance + amount; } …}

BankAccount.java

Constructor: special method that handles initialization

Constructor name must match the name of class

In this example, creation of bank account objects may indicate an initial balance

Page 9: Java Programming Review (Part I) Enterprise Systems Programming.

Object creation and method invocation

public class TestAccounts{

public static void main( String args[] ){ BankAccount b = new BankAccount(); BankAccount x = new BankAccount( 5000.00 ); b.deposit( 1000.00 ); b.withdraw( 100.00 ); System.out.println( b.getBalance() ); x.deposit( 2000.00 ); b.deposit( 2000.00 ); System.out.println( b.getBalance() ); System.out.println( x.getBalance() );}

}

TestAccounts.java Object creation done through the new keyword

Method invocation done through the dot notation

object.method( params )

Page 10: Java Programming Review (Part I) Enterprise Systems Programming.

Java naming conventions Class names

Start with a capital letter, capitalize first letters of succeeding words

Examples: BankAccount, MyClass, WelcomeServlet Variable and method names

Start with a lowercase letter, capitalize first letters of succeeding words

aka “camelCase” Examples: balance, firstName, favoriteNumber

Following these conventions make your programs easier to read!

Page 11: Java Programming Review (Part I) Enterprise Systems Programming.

Types in Java Primitive types: one of the 8 built-in types in Java

int, double, long, short, byte, float, char, boolean Variables of primitive types hold values acceptable

under these types Object types: classes

Some of these types are “built-in” (present in the Java library) such as String or System, the rest are user-defined such as BankAccount or WelcomeServlet

Variables of object types hold references to objects

Page 12: Java Programming Review (Part I) Enterprise Systems Programming.

Variables for built-in types Variables for built-in types

int x; …x = 5;

5

x

x

Page 13: Java Programming Review (Part I) Enterprise Systems Programming.

Variables for object types Object (reference) type variables

BankAccount x; …x = new BankAccount( 1000 );

x

x

balance:1000

BankAccount Object

Page 14: Java Programming Review (Part I) Enterprise Systems Programming.

Variables and assignment Primitive variables

int x, y;x = 1000;y = x;y++;// at this point, x = 1000, y = 1001

Object variables BankAccount x, y;

x = new BankAccount( 1000 );y = x;y.deposit( 1 );// at this point, x.getBalance() is 1001,// y.getBalance() is 1001

xbalance:

1001

y

1000

x

1001

y

Page 15: Java Programming Review (Part I) Enterprise Systems Programming.

Parameter passing BankAccount b = new BankAccount(100);

int x = 100;changeAccount( b ); // update of b possiblechangeNumber( x ); // update of x not possible…void changeAccount( BankAccount c ){ c.deposit( 10 ); // b and c point to the same object }void changeNumber( int y ){ y = y + 10; // y changes, but x does not}

In the above code, since b is a reference to an object, that object could be changed by the method.

The same does not hold for x. The value of x is copied into y. Changes to y does not impact on x.

Page 16: Java Programming Review (Part I) Enterprise Systems Programming.

The null keyword Set an object variables to null when you

want the variable to not refer to an object null is a reserved word in Java

Can be used to initialize object variables BankAccount x = null;

You may test for null first before you call methods on an object variable if ( x != null )

System.out.println( x.getBalance() );

Page 17: Java Programming Review (Part I) Enterprise Systems Programming.

The this keyword When within a class and you wish to refer

to the current object, use the this keyword this is a reserved word in Java

Can use the dot notation within a class when referring to fields/methods public void deposit( double amount )

{ this.balance = this.balance + amount;}

Page 18: Java Programming Review (Part I) Enterprise Systems Programming.

Arrays Array variables are object references

type[] arrayVar; Array creation done separately

arrayVar = new type[size]; Applicable for both primitive types and

object types Note: for an array of objects, array

creation creates object references Individual objects need to be created

separately

Page 19: Java Programming Review (Part I) Enterprise Systems Programming.

Array of numbers

Declare: double[] nums;

nums

Page 20: Java Programming Review (Part I) Enterprise Systems Programming.

Array of numbers

Declare: double[] nums;

Create: nums = new double[8];

nums 0.0

0.0

0.0

0.0

0.0

0.0

0.0

0.0

0

1

2

3

4

5

6

7

0.0

Page 21: Java Programming Review (Part I) Enterprise Systems Programming.

Array of numbers

Declare: double[] nums;

Create: nums = new double[8];

Use: nums[3] = 6.6;

nums 0.0

0.0

0.0

0.0

0.0

0.0

0.0

0.0

0

1

2

3

4

5

6

7

6.6

Page 22: Java Programming Review (Part I) Enterprise Systems Programming.

Array of objects

Use objects: e.g., accounts[3].getBalance(); (returns 30)

Create array: accounts = new BankAccount[5];

Declare: BankAccount[] accounts;

accounts

Create objects:for ( i = 0; i < 5; i++ ){ accounts[i] = new BankAccount(i * 10);}

null0

1

2

3

4

null

null

null

null

null

BankAccount-type references

BankAccount balance 40

BankAccount balance 30

BankAccount balance 20

BankAccount balance 10

BankAccount balance 0

Page 23: Java Programming Review (Part I) Enterprise Systems Programming.

Inheritance Inheritance: an object-oriented

programming language feature that allows for the definition of a class in terms of another class

In Java, use the extends keyword Promotes reusability of existing code

Page 24: Java Programming Review (Part I) Enterprise Systems Programming.

Example: CheckingAccount Suppose we define CheckingAccount from scratch Attributes

balance number of checks drawn

Methods deposit withdraw get balance draw a check …others

CheckingAccount

double balanceint numChecks

double getBalance()void deposit( double amount )void withdraw( double amount )void drawCheck( double amount )…others

Page 25: Java Programming Review (Part I) Enterprise Systems Programming.

Example: CheckingAccount Resulting class is very similar to

BankAccount The same as BankAccount except for an

additional field and some methods Better to extend BankAccount instead

Page 26: Java Programming Review (Part I) Enterprise Systems Programming.

BankAccount revisitedpublic class BankAccount{ private double balance = 0; public double getBalance() { return balance; } public void deposit( double amount ) { balance = balance + amount; } public void withdraw( double amount ) { balance = balance - amount; }}

Page 27: Java Programming Review (Part I) Enterprise Systems Programming.

public class CheckingAccount{ private double balance = 0; private int numChecks = 0;

public int getBalance() { return balance; } public void deposit( double amount ) { balance = balance + amount; } public void withdraw( double amount ) { balance = balance - amount; } public void drawCheck( double amount ) { balance = balance - amount; // or, withdraw( amount ); numChecks++; } public int numChecksDrawn() { return numChecks; }}

CheckingAccount.java

Just like BankAccount except for the code in bold

Page 28: Java Programming Review (Part I) Enterprise Systems Programming.

public class CheckingAccount extends BankAccount{ private int numChecks = 0;

public void drawCheck( double amount ) { withdraw( amount ); // can’t do balance = balance – amount; // because balance is private to BankAccount numChecks++; } public int numChecksDrawn() { return numChecks; }}

CheckingAccount.java

Using extends

Notice that (public) methods defined in BankAccount (e.g., withdraw) can be used within CheckingAccount

Page 29: Java Programming Review (Part I) Enterprise Systems Programming.

Using CheckingAccount objects

CheckingAccount mary = new CheckingAccount();mary.deposit( 1000 );System.out.println( “Balance: ” + mary.getBalance() );mary.drawCheck( 100 );System.out.println( “Balance: ” + mary.getBalance() );System.out.println( “Checks Drawn: ” +

mary.numChecksDrawn() );

Can call methods defined in BankAccount

… and methods defined in CheckingAccount

Page 30: Java Programming Review (Part I) Enterprise Systems Programming.

Superclass variables, subclass objects Checking accounts are bank accounts so it is

possible to have a BankAccount variable point to a CheckingAccount object

But not the other way around Superclass variables can refer to subclass

objects, not vice-versa BankAccount b1 = new CheckingAccount();

(note: only methods indicated in BankAccount may be invoked through b1)

CheckingAccount b2 = new BankAccount();(not allowed because a bank account is not necessarily a checking account)

Page 31: Java Programming Review (Part I) Enterprise Systems Programming.

Method overriding A subclass may define a method already in

the superclass: this is called method overriding

The subclass method takes precedence over the superclass method Suppose class A extends class B and both

classes define a method m() B x = new A();

x.m(); // calls the method defined in A, not B If you call m() within class A, this pertains to

class A’s m(). To call B’s m(), use super.m()

Page 32: Java Programming Review (Part I) Enterprise Systems Programming.

Inheritance and constructors

public class BankAccount{ private double balance;

public BankAccount() { balance = 0; } public BankAccount( double initBal ) { balance = initBal; } public double getBalance() { return balance; } public void deposit( double amount ) { balance = balance + amount; } public void withdraw( double amount ) { balance = balance - amount; }}

public class CheckingAccount extends BankAccount{ private int numChecks;

public CheckingAccount() { numChecks = 0; } public void drawCheck( double amount ) { withdraw( amount ); numChecks++; } public int numChecksDrawn() { return numChecks; }}

CheckingAccount c = new CheckingAccount();

Which of the constructors are called?

Page 33: Java Programming Review (Part I) Enterprise Systems Programming.

Inheritance and constructors

CheckingAccount = new CheckingAccount();

In the above statement, CheckingAccount’s (default) constructor is called

Since CheckingAccount is a BankAccount, a BankAccount constructor should also be called Which one? Answer: the default constructor Note that BankAccount() is called before

CheckingAccount() What if we want a particular constructor of a

superclass called?

Page 34: Java Programming Review (Part I) Enterprise Systems Programming.

Incorrect attempt

public class CheckingAccount extends BankAccount{ private int numChecks;

public CheckingAccount() { numChecks = 0; } public CheckingAccount( double startBal ) { numChecks = 0; } public void drawCheck( double amount ) { withdraw( amount ); numChecks++; } public int numChecksDrawn() { return numChecks; }}

We want CheckingAccount c = new CheckingAccount( 1000 );to create an account with an initial balance of 1000

This will still callBankAccount( ),notBankAccount( 1000 )

Page 35: Java Programming Review (Part I) Enterprise Systems Programming.

Using super()

public class CheckingAccount extends BankAccount{ private int numChecks;

public CheckingAccount() { numChecks = 0; } public CheckingAccount( double startBal ) { super( startBal ); numChecks = 0; } public void drawCheck( double amount ) { withdraw( amount ); numChecks++; } public int numChecksDrawn() { return numChecks; }}

•super( … ) indicates which superclass constructor will be called•If not indicated, it defaults to super( ) with no parameters•Call to super(…) should be the first line in the subclass’ constructorImplicitly calls

“super();” or BankAccount( )

Calls a particular constructorBankAccount( int )

Page 36: Java Programming Review (Part I) Enterprise Systems Programming.

Interfaces in Java Interface: collection of method signatures with no

bodies Syntax

public interface InterfaceName{ public type methodName1(…); public type methodName2(…); …}

A java class may implement an interface

public class ClassName implements InterfaceName{ // define methodName1, methodName2, ... here}

Page 37: Java Programming Review (Part I) Enterprise Systems Programming.

Two types of inheritance Class inheritance (extends)

public class A extends B { … } Class A inherits fields and methods in class B public methods of B can be invoked on A objects, unless

overridden in A Interface inheritance (implements)

Also called implementation inheritance public class X implements Y { … } X must define all methods indicated in Y

Page 38: Java Programming Review (Part I) Enterprise Systems Programming.

Why use interfaces? Interfaces enable and enforce “strict” sharing of

methods among classes Recall that superclass variables can refer to

subclass objects Suppose Y is an interface

Y var; var can refer to an object of a class that implements Y var.methodName( … ) calls the actual method defined

Page 39: Java Programming Review (Part I) Enterprise Systems Programming.

Example: Shape A Shape is anything that can be drawn:

public interface Shape{ public void draw();}

Any class that implements Shape must implement the draw() method

Suppose Block, Triangle, and LetterT implement shape

We can have an array of Shapes with elements referring to different kinds of objects Use a loop to call draw() on all of the shapes

Page 40: Java Programming Review (Part I) Enterprise Systems Programming.

Example: Shape (and Block)public class Block implements Shape{ private int size; public Block( int s ) { size = s; } public void draw() { for( int i = 1; i <= size; i++ ) { for( int j = 1; j <= size; j++ ) System.out.print( “*” ); System.out.println(); }}

Because it implements Shape,this class will not compile unlessdraw() is defined

Page 41: Java Programming Review (Part I) Enterprise Systems Programming.

Example: array of Shapes

null

Shape[] list;…for ( int i = 0; i < 5; i++ ){ list[i].draw( );}

0

1

2

3

4

null

null

null

null

null

list Blockobject

Triangle object

LetterT object

Block object

Triangle object

Page 42: Java Programming Review (Part I) Enterprise Systems Programming.

Multiple inheritance Multiple (class) inheritance is not

supported in Javapublic class A extends B1, B2, B3 { … }

But a class may implement multiple interfacespublic class X implements Y1, Y2, Y3 { … }

will not compile

will compile, but X must define methods in Y1, Y2, and Y3

Page 43: Java Programming Review (Part I) Enterprise Systems Programming.

About interfaces Interfaces cannot be instantiated

Shape s = new Shape(); Interfaces can be extended

public interface Y1 extends Y2 { … } public class X implements Y1 { … }

X must define methods indicated in Y1 and Y2 Interfaces cannot declare instance fields and may

not have any method definitions Use an abstract class instead