440 likes | 467 Views
Learn Java programming basics including classes, packages, objects, arrays, inheritance, exceptions, files, and more. Understand Java core concepts and execution techniques. Develop Java programs with clear naming conventions.
E N D
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
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
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
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.*;
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 { … }
BankAccount.java public class BankAccount { private double balance = 0; public double getBalance() { return balance; } public void deposit( double amount ) { balance = balance + amount; } … } Class definition in Java BankAccount • Type (or class) • State/attributes (fields) • Behavior (methods) • Code for object creation(usually) done outsideof this class
BankAccount.java 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; } … } A Class with a constructors • 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
TestAccounts.java 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() ); • } • } Object creation and method invocation • Object creation done through the new keyword • Method invocation done through the dot notationobject.method( params )
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!
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
Variables for built-in types • Variables for built-in types int x; … x = 5; x x 5
Variables for object types • Object (reference) type variables BankAccount x; … x = new BankAccount( 1000 ); x BankAccount Object balance:1000 x
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 x y 1000 1001 balance:1001 x y
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.
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() );
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;}
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
Array of numbers nums Declare: double[] nums;
0.0 0 0.0 1 0.0 2 0.0 3 0.0 4 0.0 5 0.0 6 0.0 7 Array of numbers nums 0.0 Declare: double[] nums; Create: nums = new double[8];
0.0 0 0.0 1 0.0 2 0.0 3 0.0 4 0.0 5 0.0 6 0.0 7 Array of numbers nums 6.6 Declare: double[] nums; Create: nums = new double[8]; Use: nums[3] = 6.6;
null null null null null BankAccount balance 0 BankAccount balance 10 BankAccount balance 20 BankAccount balance 30 BankAccount balance 40 Array of objects BankAccount-type references accounts 0 null 1 Declare: BankAccount[] accounts; 2 3 Create array: accounts = new BankAccount[5]; 4 • Create objects: • for ( i = 0; i < 5; i++ ){ accounts[i] = new BankAccount(i * 10);} Use objects:e.g., accounts[3].getBalance(); (returns 30)
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
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 balance int numChecks double getBalance() void deposit( double amount ) void withdraw( double amount ) void drawCheck( double amount ) …others
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
BankAccount revisited public 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; } }
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
Using extends 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 Notice that (public) methods defined in BankAccount (e.g., withdraw) can be used within CheckingAccount
Using CheckingAccount objects Can call methods defined in BankAccount 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() ); … and methods defined in CheckingAccount
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)
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()
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?
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?
Incorrect attempt We want CheckingAccount c = new CheckingAccount( 1000 );to create an account with an initial balance of 1000 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; } } This will still call BankAccount( ),not BankAccount( 1000 )
Using super() • 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’ constructor 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; } } Implicitly calls “super();” or BankAccount( ) Calls a particular constructor BankAccount( int )
Interfaces in Java • Interface: collection of method signatures with no bodies • Syntaxpublic interface InterfaceName{ public type methodName1(…); public type methodName2(…); …} • A java class may implement an interfacepublic class ClassName implements InterfaceName{ // define methodName1, methodName2, ... here}
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
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
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
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
Example: array of Shapes Blockobject list null 0 null 1 Triangle object null 2 null null 3 LetterT object Shape[] list;… 4 null for ( int i = 0; i < 5; i++ ){ list[i].draw( ); } Triangle object Block object
Multiple inheritance • Multiple (class) inheritance is not supported in Java public class A extends B1, B2, B3 { … } • But a class may implement multiple interfaces public class X implements Y1, Y2, Y3 { … } will not compile will compile, but X must define methods in Y1, Y2, and Y3
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