520 likes | 530 Views
Learn advanced Java programming techniques and fundamental concepts of programming languages. Understand OOP principles like Abstraction, Encapsulation, Inheritance, and Polymorphism. Dive into Object-Oriented Analysis and Design, Java SDK, and Design Patterns. Enhance your Java skills and system knowledge.
E N D
MT311 (Oct 2006)Java Application Development Tutorial 1 Object-Oriented Programming in Java
Tutor Introduction • Edmund Chiu (Group 1) • Email: gianted@netvigator.com ORt439934@ouhk.edu.hk • Please begin your email subject with [MT311]
What is MT311? • Not a basic Java programming course • Fundamental knowledge of programming should have been learned in MT201 and/or MT258 • You can refer to Java Tutorial (http://java.sun.com/docs/books/tutorial/) to learn the basic technique of Java programming
What is MT311? • Not only teaching you advanced Java programming technique • It teach you the concepts of programming languages • Why they are designed as they are • Which language is the best for my system
What is needed? • J2SE 1.5 SDK – You can’t write a Java program without it!! • http://java.sun.com/j2se/1.5/download.html • NOT NetBeans IDE nor J2EE nor J2SE JRE • TextPad – A simple editor with Java syntax highlight • http://www.textpad.com • Java files can be compiled and run directly in TextPad • You may also choose to use other IDE you familiar with • Java API Specification • http://java.sun.com/j2se/1.5/docs/api/ • List out all packages, classes and their details
Object-Oriented Progrmming • In object-oriented programming, a program consists of objects interaction through method invocation • Four basic principles in OOP • Abstraction • Encapsulation • Inheritance • Polymorphism
Abstraction • Everything in OOP is an object • Abstraction of real world entities and behaviors into objects • Example: In a banking system, Account is an object owning its state (e.g. balance) and behavior (e.g. deposit and withdraw operations)
Encapsulation • Information Hiding • Only interface is provided to others and actual implementation is hidden • Focus on the functional behaviours but not the implementation details • more modular – implementation can be updated in a more flexible way • We can now control the accessibility and visibility of variables and methods • Example: balance in the Account should be read-only. Balance change must be done through withdraw and deposit methods
Inheritance • Extends an object by inheriting the behaviours (data and/or operations) of another object • Behaviours of the original object can be modified • New features can be added • An is-a relationship between a parent-class (superclass) and the child-class (subclass) • Example: overdraft-account is inherited from Account with extended features – an overdraft account is still an account.
Polymorphism • Literally means multiple forms • In OO, polymorphism have several meanings • Overloading of methods/operators –same method name, a different argument list • Dynamic binding of methods –when a method is over-ridden in the subclass (same method name, same list of argument), which methods (superclass/subclass) should be called when the subclass object is used in place of superclass object?
Overloading and Overriding • Example in overloading operator (+) • + can mean integer addition, floating point addition or even String concatenation • Normally, it makes program more readable and concise, but does not give new meaning to the language • Example in over-riding and dynamic binding • Overdraft-account can be manipulate as an overdraft-account or a normal account • When withdraw from account method is called, should it be the withdraw method from account class, or from the overdraft-account class • In Java, binding is done dynamically – the runtime inspects the object’s actual type
Object-Oriented Analysis and Design (OOAD) • Systematic steps for analyzing a problem and designing a solution in an OO way • Analyze the problem domainYou may need to research and/or consult the domain experts • Identify the objects and their relationship in the problemYou may need a visual language (namely UML) to draw out the interacting parties and their interactions • Abstract the objects into Java objects/classesUsing real word as a framework to make it easier to model and be understood
Design Patterns • A Design Pattern is a high-level proven solution for solving a particular type of problem. • Well implemented and used by previous practitioners • Very useful for less experienced programmers • It is sufficient to know the basics of patterns, especially how to use it
Examples of Design Patterns • Observer Pattern • Linking Event source and Event listener may become unwieldy in large system • In observer pattern, a source is Observable and the listeners are Observers • After registration, when a relevant event happens in the Observable, the observers will be notified automatically • Model-View-Controller (MVC) • View represents the user interface • Control is the application controller • The core data and logic is stored in model • Maps well in n-tier application, e.g., Web systems.
Object Modeling with UML • Map a solution to object • A popular tool for OOAD is UML, Universal Modeling Language • A graphical language • Can model the whole software design and be used throughout the development process • It can be used in capturing system requirements, module boundaries and interactions, object mapping, code generation and even physical deployment. • You need not to have a full understanding of UML in this course, but a basic knowledge of UML should be useful
Documentation using JavaDoc and UML • Proper documentation has been a big headaches throughout the professional system development • Java provides a tool called JavaDoc making the documentation an integral part of code development • By inserting specific comments and tags, programmers can run JavaDoc to create proper documentation for their code • UML diagrams are now also widely used as a documentation language • There are even UML extension to JavaDoc enabling the generation of UML diagrams from the code
Basic Java • The following pages introduce you the most basic components of the Java language • Data structure – how data is represented • Program statements – how to express a computation • Control structures – how to control the execution • Compiling and linking – how to compile and link code into executable applications
Variables • Variables are identifiers to some data structure • Two types of data structures in Java –objects and primitive types • Apart from the numeric and boolean data types such as long, int, float, double, char and etc., all data are represented as objects in Java. • The main differences in handling the two types are: • How they are created (declared) • How they are used in method invocations • As Java is a strictly typed language, all variables must be declared with their types before used: • Syntax: <type> <variable_name>
Expression, Statements and Blocks • Variables become expression when combined by operators • Expressions when combined become program statements • Example: c = a+b; • Statements are separated by a semicolon ; and multiple statements can be combined into a block using braces { } • Example: { a = 1; b = 2; c = a + b; }
Selection statements If-else: if (a>b) max = a; else max = b; Switch-case:switch(x) { case 1: y=1; break; case 2: y=1; break; default: y=x*2; } Looping For:for(int i=0; i<5; i++) { sum += i;} While:while(a.hasNext()) { System.out.println(a.next());} Do…while Control Flow Statements
Control Flow Statements (cont’d) • Exception handling statements • Try-catch-finallywill be further discussed when in use • Throw statement • Branching statements • Break(i) leave a loop prematurely(ii) leave a switch statement • Continuejump to next iteration in a loop • Returnleave a method
Linking with Other Classes • In Java, related classes can be organized into packages • Some support classes in a package is hidden from other classes outside the package – another kind of encapsulation • Organize a class into a package by simply add the package statement at the top of the program:package myPackage; • To reference classes from another package, you need to have an import statement at the top of the program • Example: import java.io.*; • Java provides many packages you can use. • For details, consult the API specification
Application version public class HelloWorldApp { public static void main(String[] args) { // Display "Hello World!" System.out.println("Hello World!"); } } Applet version import java.applet.*; import java.awt.*; public class HelloWorld extends Applet { public void paint(Graphics g) { // Display "Hello World!" g.drawString("Hello world!", 50, 25); } } My First Cup of Java
Defining a Class • Example: we are to model a bank account, we need to have a state (balance) and two operations (withdraw and deposit) class BankAccount { double balance;double withdraw(double amount) {…}double deposit(double amount) {…} }
Narrowing the Public Interface • We need to prevent user from directly modifying balance, but still providing the accessibility of balance to our subclasses. The account balance should be read-only through the accessor method public class BankAccount { protected double balance;public double withdraw(double amount) {…}public double deposit(double amount) {…}public double getBalance() {…} }
Creating an Object • We use the new keyword to create (instantiate) an object BankAccount acc = new BankAccount(); • The new keyword will allocate the memory for the object and call the specified constructor. A reference to the created object will be returned. • Constructor, in general, is used to perform object initialization – initialization of instance variables and performing superclass intialization • Complex initialization should be done through calling methods • If no constructor is given in the class, default constructor will be used (no argument, do nothing)
Constructor and Examples • It’s a good programming practice to define the constructor even it does nothing • Unlike other methods, constructors have the same name as the class and no return type • Like other methods, constructors can be overloaded with different argument list public class BankAccount { protected double balance;public BankAccount () { balance = 0.0; }public BankAccount (double initBalance) { balance = initBalance; }… }
Finalizer • In C/C++, programmer needs to write destructors for memory management – release the memory at the end of a variable’s life • In Java, programmer needs not to take care of the memory management, garbage collection in Java VM will remove the unused objects • In Java, finalizer is called automatically just before the object is garbage-collected • No guarantee of running – if there is no need of garbage collection till the end of execution, the finalizer will never be called • Though no side effect will happen by calling finalizer explicitly multiple times, programmers should do the final swap up in a user-defined method like close() and etc.
Instance Member • To reference an instance variable (belongs to the object), we need to have an object instance first • Example: to perform withdraw operation, we must have a BankAccount first BankAccount acc = new BankAccount(500.0); acc.withdraw(300.0);
Static Methods and Variables • Static variables and methods belong to the class rather than to a specific instance of class • Example: you may have a common interest rate for all savings account:static double commonRate = 0.05; • All instances will then share the same variable commonRate • Static variables/methods can be called without creating any object: double specialRate = BankAccount.commonRate + 0.01; • Static methods cannot refer to non-static member in the class • Static method is called through the class and does not have (this) object reference
In Java, almost everything is an object Primitive data type are made for more convenience for the programmers In Java, an object is defined in a class States of an object stored as member variables Behaviours are manifested via methods Example: BankAccount class BankAccount { double balance;double withdraw(double amt) {…}void deposit(double amt) {…} } Abstraction in Java
Encapsulation in Java • Variables and methods are bundled inside classes (which may be packed into packages) • Access modifiers are used to determine the visibility of classes, methods and variables • Public – open to all classes • Private – hide from all classes except itself • Protected – open to subclasses (and itself) only • Default – open to classes of same package (folder) • Usually in OOP, we hide the member variables (protected/private) and give get/set (accessor/mutator) methods for reading and writing the variables
Encapsulation Example • In our bank account, we should: • Apply protected to balanceto avoid direct access to balance by other classes except those which is its subclass • Provide get method for balance onlymake balance read-only, need to call withdraw/deposit to change the balance value public class BankAccount { protected float balance; public double withdraw(double amt) {…} public void deposit (double amt) {…} public double getBalance() {…}}
Inheritance in Java • Inheritance in Java is supported through the keyword extends • class B extends A means B is the subclass, A is the superclass • Example: public class OverdraftAccount extends BankAccount { public double withdraw(double amt) { // override } } • In the above example, withdraw method is overriden, but other methods (deposit, getBalance) are the same as in BankAccount
Construction and Destruction of Inherited Objects • When constructing a subclass object, the constructor of the superclass will be called, either explicitly or implicitly • Java will call super class default constructor (no argument) if no explicit call to superclass constructor is existed • Call of superclass constructor must be made as the first statement in the constructor method body • The same applies to finalizers
class A { public A() { System.out.println ("Constructor A is called."); } } class B extends A { public B() { System.out.println ("Constructor B is called."); } } class C extends B { public C() { System.out.println ("Constructor C is called."); } public C(int i) { System.out.println ("Constructor C with " + i + " is called."); } } class D extends C { public D(int i) { System.out.println ("Constrcutor D with " + i + " is called."); } } class E extends C { public E(int i) { super(i); System.out.println("Constructor E with " + i + " is called."); } } class TestConstructor { public static void main(String args[]) { B b = new B(); System.out.println("===="); C c = new C(); System.out.println("===="); D d = new D(10); System.out.println("===="); E e = new E(100); } } Example of Constructor in Inheritance
Polymorphism in Java • Overloading • Methods using same name must have different number/type of parameters • Overriding • Methods in subclass can use the same method name with same signature to define a new meaning for the method • Interface • Specification without implementation • A class can provide the specified features by implementing the interface • One use of interface is to enforce typingExample: sorting function can take comparable objects only
Dynamic Binding and Polymorphism • Binding refers to the resolution of which form of overloaded methods is to be used • Traditional languages use static binding – the binding is determined in the compile time • Java uses dynamic binding – the binding is determined in the run time by the Java VM • Dynamic binding is more flexible and powerful but requires more resource because binding is to be resolved at each invocation
Polymorphism Example • Which withdraw will be called? BankAccount a = new OverdraftAccount(0.0, 50.0); a.withdraw(25.0); // call overdraft’s withdraw BankAccount b = new BankAccount(100.0); b.withdraw(25.0); // call bankAccount’s withdraw f1(a); // call overdraft’s withdraw f2(a); // call overdraft’s withdraw f1(b); // casting error f2(b); // call bankAccount’s withdraw double f1 (OverdraftAccount a) { return a.withdraw(25.0); } double f2 (BankAccount a) { return a. withdraw(25.0); }
Abstract Classes • An abstract class is similar to interface, but it may provide partial implementation • Abstract class is not instantiable, but you can inherit it and provides the missing implementation and make it instantiable. • Interface is usually used to define roles played by a class • Abstract class is often used as the base class of a family of classes
Examples on Interface and Abstract Class • public class SavingsAccount implments AutoPay • Autopay is not really an entity and should not be defined as class • An object of SavingsAccount can be casted into AutoPay and uses the methods in AutoPay • public abstract class GeneralAccountpublic class SavingsAccount extends GeneralAccount • Some common attributes and methods are defined in GeneralAccount, some methods may be abstract (e.g getBalance()) • All subclasses of GeneralAccount should be concrete classes and provide the services defined in GeneralAccount, including the implementation of those abstract methods
Final Methods and Classes • Final methods cannot be overridden and final classes cannot be subclassed • Prevent undesirable method overriding • Prevent subclassing that may undermine the design integrity • Example: you don’t want other to alter the way you worked in your security manager class • Final method/class binds the memory statically
Object and Class Classes • All objects in Java are subclass of the root class Object • Some common methods of object:cloning, equality, threading, string representation and etc. • Enable us to write generic collection without using templatesExample: a vector stores a collection of Objects • Type casting is used to cast the Object to its original class • The Class class provides runtime information • getClass() in Object class returns a Class object reference • Using the Class object, you can grab some runtime information about the class (e.g. class name, is it an array and etc.) • Instanceof operator can also used to check if an object is an instance of a classExample: if (acc instanceof SavingsAccount) { // do something }
Cloning Objects • The assignment operator do not copy the objects • Example: Pair x = new Pair(5, 6); Pair y = new Pair(14, 16); x = y;Reference x will be pointing to the same object as y • To make a copy of an object, we use the clone method • Example: Pair x = new Pair(5, 6); Pair y = new Pair(14, 16); x = (Pair) y.clone();Reference x will be pointing to a separate copy of y • To enable an object of a class to use clone method, it must implement Cloneable (code: Quiz2_5, Pair)
Shallow and Deep Copies • The default clone is only performing a shallow copy • Create a new object with all attributes assigned using assignment operator (=) • If the object is storing another object, the result will be unexpected • Example: if b is a.clone() and a has an object (o) as its attribute: when a.o is changed, it will also affect b.o a.o and b.o is referring to the same object • We need to override the default clone() method to perform a deep copy
Nested Class, Inner Class and Anonymous Class • You can use the complete Java language without knowing anything about inner classes. • These inner classes are used to make code more elegant and improve the structure of a class
Nested Class public class outer { // the nested class … public static class inner { // enclosing class… }} • Nested classes are top-level classes and not associated with instances of enclosing classes • Nested class has no special privileges for accessing members of enclosing class • Nested class can show a close relationship between the nested and enclosing class, without a tight coupling of data within two classes
Inner Class • When you instantiate an inner class and the class encloses it, the two objects are crated with access to the same copies of the outer class • One benefits is that the inner class having the access to internal variables and methods can provide an effective implementation to some adaptor interface
Anonymous Inner Class • When a local inner class cannot be referenced outside the block in which the class is defined, we may choose to given no name to it, making it an anonymous inner class. • Example: new MouseListener() {// some necessary methods here }