Java Programming Review (Part I) Enterprise Systems Programming.

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Advertisements

Lab Information Security Using Java (Review) Lab#0 Omaima Al-Matrafi.
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Lab#1 (14/3/1431h) Introduction To java programming cs425
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
9. Inheritance 9.1 Subclasses 9.2 Polymorphism 9.3 Abstract Classes 9.4 Modifiers and Access 9.6 Object-Oriented Design with Use Cases and Scenarios.
Road Map Introduction to object oriented programming. Classes
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Introduction to Java CS 331. Introduction Present the syntax of Java Introduce the Java API Demonstrate how to build –stand-alone Java programs –Java.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Chapter 10 Classes Continued
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
OOP Languages: Java vs C++
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Introduction to Object-Oriented Programming
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Introduction to Java and Object-Oriented Programming AJSS Computer Camp Department of Information Systems and Computer Science Ateneo de Manila University.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Programming Languages and Paradigms Object-Oriented Programming.
Classes CS 21a: Introduction to Computing I First Semester,
Programming Languages and Paradigms Programming C++ Classes.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Introduction to Java Java Translation Program Structure
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Inheritance A Review of Objects, Classes, and Subclasses.
Pengantar OOP Class-Java. 2 Software Development Tools Using Sun Java SDK alone Source File(s) (.java) Programmer Compiler (javac) Class File(s) (.class)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Using Objects. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L7: Objects Slide 2 Java.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Object Oriented Programming
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
OOP Basics Classes & Methods (c) IDMS/SQL News
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Java Interfaces CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (see Chapter 9 of.
2-Oct-16 Basic Object-Oriented Concepts. 2 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions,
Java Primer 1: Types, Classes and Operators
OBJECT ORIENTED PROGRAMMING II LECTURE 7 GEORGE KOUTSOGIANNAKIS
Chapter 3 Introduction to Classes, Objects Methods and Strings
Java Programming Language
Object Oriented Programming in java
Classes CS 21a: Introduction to Computing I
Introduction to Object-Oriented Programming
Chap 2. Identifiers, Keywords, and Types
Presentation transcript:

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 must be 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 { … }

Class definition in Java BankAccount Type (or class) State/attributes (fields) Behavior (methods) Code for object creation (usually) done outside of this class public class BankAccount { private double balance = 0; public double getBalance() { return balance; } public void deposit( double amount ) { balance = balance + amount; } … } BankAccount.java

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

Object creation and method invocation public class TestAccounts { public static void main( String args[] ) { BankAccount b = new BankAccount(); BankAccount x = new BankAccount( ); b.deposit( ); b.withdraw( ); System.out.println( b.getBalance() ); x.deposit( ); b.deposit( ); 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 )

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; 5 x x

Variables for object types  Object (reference) type variables BankAccount x; … x = new BankAccount( 1000 ); x x balance: 1000 BankAccount Object

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 balance: 1001 y 1000 x 1001 y

Parameter passing  BankAccount b = new BankAccount(100); int x = 100; changeAccount( b ); // update of b possible changeNumber( 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 Declare: double[] nums; nums

Array of numbers Declare: double[] nums; Create: nums = new double[8]; nums

Array of numbers Declare: double[] nums; Create: nums = new double[8]; Use: nums[3] = 6.6; nums

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); } null BankAccount-type references BankAccount balance 40 BankAccount balance 30 BankAccount balance 20 BankAccount balance 10 BankAccount balance 0

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

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

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

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 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 call BankAccount( ), not BankAccount( 1000 )

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’ constructor Implicitly calls “super();” or BankAccount( ) Calls a particular constructor BankAccount( int )

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 }

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 unless draw() is defined

Example: array of Shapes null Shape[] list; … for ( int i = 0; i < 5; i++ ) { list[i].draw( ); } null list Block object Triangle object LetterT object Block object Triangle 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