Title: Java OOP Overview
1Java OOP Overview
2Course Objectives
- Upon completing this course you should be able
to - Describe the three main OOP concepts.
- Differentiate between is-a and has-a
Relationships. - Use Java standards for coding.
- Describe the Java environment and how it works.
- Write java programs.
- Create objects out of classes.
- Create classes and interfaces.
- Use Java I/O capabilities.
- Use the Java API.
- Create and manage a hierarchy of classes and
interfaces. - Create packages and document them.
- Connect to a database using JDBC.
3Course Organization
- Part 1 OOP Model
- Part 2 Java Basics
- Part 3 Java implementation of OOP Model
- Part 4 Java OO Design Issues
- Part 5 Introduction to the Java API
- Introduction to Swing
- Java I/O
- Exception Handling
- Java JDBC
- The Collection Framework
- Threads
- More
4Part 1
5Objects
- Objects can be described in terms of
- Their attributes
- Their behaviors
- Their interactions
- Objects attributes and behaviors are
encapsulated together as a data type. - Objects have a lifecycle
- Creating objects
- Manipulating objects
- Cleaning up objects
6OOP Five Rules
- Alan Kay summarized five basic characteristics of
Smalltalk - Everything is an object.
- A program is a bunch of objects telling each
other what to do by sending messages to each
other. - Each object has its own memory made up of other
objects. - Every object has a type.
- All objects of a particular type can receive the
same messages.
7Objects have Interfaces
- An object has to have an interface.
- The interface will provide a way to let other
objects communicate with it. - It will also hide the details of the objects
implementation. - An example A lightbulb!
8OOP Big Goals (1)
- Hiding the Implementation!
- Breaks up the playing field into
- Class creators (those who create new data types)
- Client programmers (those who use these types for
their own tasks. They only deal with the
interfaces.) - End users they only use the created applications
- The goal of the class creator is to build a class
that exposes only whats necessary to the client
programmer and keeps everything else hidden. - Three reasons for controlling the access
- To keep client programmers hands off portions
they shouldnt touch. - To avoid accidental (or malicious!)
changes/deletions - To allow the library designer to change the
internal workings of the class without worrying
about how it will affect the client programmer.
9OOP Big Goals (2)
- Implementation Reuse
- Software reusability is not so easy to achieve as
many would hope it takes experience and insight
to produce a good design. - OOP provides ways for reuse
- Composition
- Inheritance (Reusing the interface)
- Polymorphism
- OOP relationships between classes and objects can
be - Inheritance/Generalization (between classes)
is-a - Association (between objects) relationships
that are described as has-a - Aggregation (between objects) composed-of
(strong aggregation/composition) and
consists-of (weak aggregation) - Aggregations (weak and strong/composition) are
considered a more tightly coupled type of
association and also have the same
multiplicities/cardinalities
10OOP Big Goals (3)
- Polymorphism
- Allows you to make the derived types behave
differently from their base types. - It uses late binding instead of early binding
- Example
11Overriding or Overloading Polymorphism?
- Polymorphism translates from Greek as many forms
( poly many, morph - forms) - Method overloading is the primary way
polymorphism is implemented in Java - Overloaded methods appear in a subclass with same
name but different parameter lists and return
types - Late-binding (or run-time binding) also supports
overriding - Overriding allows a subclass to re-define a
method it inherits from it's superclass - An over-ridden method in a subclass has the same
signature (name and parameter list) and also the
same return type (different from C!)
12Program Design and Development
- The word implement means to put into effect
according to a definite plan - In software engineering, implementation is the
actual production of software (i.e., coding)
based on a plan - These plans are usually conceived during the
design phase - But the way software engineering/computer science
is taught is reversed! - First you learn how to program (code), then you
learn how to analyze and design it, finally you
learn how to (formally) figure out the
requirements/specifications!
13Software Engineering/Computer Science
- Software Development proceeds, in practice and
theory, in this manner (followed by
testing!) - However, its learned as follows (with testing in
there somewhere!) - Its taught backwards!
14Program Performance Measures
- Understand what constitutes a good implementation
- Implementation is actual production of software
(i.e., coding) - Good programs should provide
- Clarity
- Efficiency
- Not as much of an issue as the others nowadays
- Robustness
- Making it bullet-proof (to errors or misuses by
the user) - Extensibility
- Reusability
- Programming-in-the-large
- Developing large projects in a distributed manner
15Procedural vs. OO
- Procedure-oriented programming
- Has the capability of producing clear, efficient,
robust programs that can be programmed in the
large - Does not produce reusable and extensible programs
- Very cumbersome and extremely time-consuming and
costly to extend or reuse in new applications - Object-oriented technology (OOT)
- Produces both extendable and reusable code
16Moving to OOTechnology
- True OOT (Object Oriented Technology)
- One works with objects from the problem
definition stage through the programming stage - Encompasses
- OOR object-oriented requirements/specifications
- OOA object-oriented analysis
- OOD object-oriented design
- OOP object-oriented programming
- OOTe object-oriented testing
17OOLearning
- Same discrepancy in how its practiced and how
its taught!
18(No Transcript)
19Part 2
20History of C
- First there was C.
- C initially became widely known as the
development language of the UNIX OS. - C evolved as an extension to C.
- It mainly provides the capabilities of
Object-Oriented Programming to the C world. - C is a hybrid language.
- Both procedural style and object-oriented style
can be developed using C.
21History of Java
- Java was developed by James Gosling at Sun
Microsystems in 1991. - Java was initially developed to be used with
interactive TV technology which had failed to
find a market. - His original aim was to develop a low cost,
Hardware Independent Language based on C. - Due to technical reasons, that idea was dropped .
- A new programming Language called Oak was
developed based on C but removed undesirable
features of C. E.g., it removed - Multiple Inheritance
- Automatic type conversions
- Memory Management.
- Use of pointers
- By 1994 the World Wide Web Emerged and Oak was
Re-named as Java. - When The World-Wide Web became popular in 1995 ,
Java came to life again. - Java is now considered as the native language of
the Internet. - Java is a C/C based language.
- Java is a Fully object-oriented language
22So, what is Java?
- According to Sun's definition
- Java is a "simple, object-oriented, interpreted,
robust, secure, architecture-neutral, portable,
high-performance, multithreaded, and dynamic
language."
23Java Environment
24Compiling/Running Java Programs
- Write your .java source code file in any text
editor - To compile your program, use command c\gt
javac MyProgramName.java - To run your program, use command c\gt java
MyProgramName
25Java Virtual Machine
- Also called pseudo-machine or pMachine
- Hence, the bytecode generated for it is sometimes
called pCode (NOT to be confused with
pseudo-code) - Interacts with OS
26Using IDEs
- Eclipse, JCreator, BlueJ, JBuilder, and NetBeans
27Program skeleton
Notes
- //the skeleton of a java application
- package packagename
- import packagename.ClassName
- public class ProgramName
-
- // Define program variables here.
- . . .
- // Define program methods here.
- . . .
- //Define the main method here.
- public static main(String args)
-
- // Main method body
- //end of the main method.
- //End of class HelloWorld
- Java is a case sensitive language
- Braces must occur on matching pairs
- Coding styles should be followed.
28Comment Styles
- Comments are used to make clear the logic of the
code and to increase its readability. - Comments are ignored by the compiler.
- Java uses three types of comments
- Single-line comment(//). Example
//single-line comment here - Multiple-line comment(//). Example
- /
- line 1 here line 2 here
- /
- Documentation comment(//). It is
multiple-line and used with javadoc utility to
create application documentation.
29Playing With Strings
- A string is a group of characters
- We use class String to define a string. Example
String name - Strings are bounded by double quotations.
Example String name Jane - We can concatenate two or more strings using the
operator - Strings can contain escape characters like \n,
\t, \\, \.
30Variable Definitions
- Variables are used to represent the data that a
program deals with - As the name might imply, the data that a variable
holds can change. - We have to define a variable before using it
- Here are some examples of defining a
variable int number String name - Different kind of variables (class, instance, and
local) - Different default initializations
- Instance variables get default values local
variables dont
31Primitives Data types
32Arithmetic Operations
33Decision making operations
34Assignment Operators
35Increment /decrement operation
36Logical Operators
- Logical operators allow more complex conditions
- (logical AND)
- Returns true if both conditions are true
- (logical OR)
- Returns true if either of its conditions are true
- ! (logical NOT, logical negation)
- Reverses the truth/falsity of its condition
- Unary operator, has one operand
- Short circuit evaluation
- Evaluate left operand, decide whether to evaluate
right operand - If left operand of is false, will not evaluate
right operand
37Precedence
38Java Keywords
Keywords are words reserved for Java and cannot
be used as identifiers or variable names
39If if/else structures
- if statement looks like if (condition)
- Conditions are evaluated to either true or false
- If/else statement looks like
- if (condition)
-
- //do something.
-
- else
-
- //do something else.
-
40The switch Structure
- switch statements
- Useful to test a variable for different values
- switch ( value )
- case '1'
- actions
- case '2'
- actions
- default
- actions
-
- break causes exit from structure
41While Structure
- while repetition structure
- Repeat an action while some condition remains
true - while loop repeated until condition becomes false
- Body may be a single or compound statement
- If the condition is initially false then the body
will never be executed - Example
- int product 2
- while ( product lt 1000 ) product 2 product
42The for Structure
- for "does it all" initialization, condition,
increment - General format
- for ( initialization loopContinuationTest
increment ) statement - If multiple statements needed, enclose in braces
- Control variable only exists in body of for
structure - If loopContinuationTest is initially false, body
not executed
43Methods
- Methods
- Modularize a program
- Break it up into functions and objects that have
functions - All variables declared inside methods are local
variables - Known only in method defined
- Parameters
- Communicate information between methods
- Difference between actual and formal parameters
- Benefits
- Divide and conquer
- Manageable program development
- Software reusability
- Avoids code repetition
- Existing methods are building blocks for new
programs - Hides unnecessary details
- Abstraction - hide internal details (library
methods)
44Method Definitions
- Method definition format
- return-value-type method-name( parameter-list
) declarations and statements - Method-name any valid identifier
- Return-value-type data type of the result
(default int) - void - method returns nothing
- Can return at most one value
- An access modifier (later)
- Parameter-list comma separated list, declares
parameters.
45return Statement
- When method call encountered
- Control transferred from point of invocation to
method - Returning control
- If nothing returned return
- Or until reaches right brace
- If value returned return expression
- Returns the value of expression
- Example user-defined method
- public int square( int y )
- return y y
-
46Calling methods
- Three ways
- Method name and arguments
- Can be used by methods of the same class within
that class - square( 2 )
- Dot operator - used with references to objects
- g.drawLine( x1, y1, x2, y2 )
- Dot operator - used with static methods of
classes by using the Class name - Integer.parseInt( myString )
47Coercion of arguments
- Forces arguments to appropriate type for method
- Example
- Math methods only take double
- Math.sqrt( 4 ) evaluates correctly
- Integer promoted to double before passed to
Math.sqrt - Promotion rules
- Specify how types can be converted without losing
data - If data will be lost (i.e. double to int),
explicit cast must be used - If y is a double,
- square( (int) y )
48Duration of Identifiers
- Duration (lifetime) of identifiers
- When exists in memory
- Automatic duration
- Local variables in a method
- Called automatic or local variables
- Exist in block they are declared
- When block becomes inactive, they are destroyed
- Static duration
- Created when defined
- Exist until program ends
- Does not mean can be referenced/used anywhere
- See Scope Rules
49Scope Rules (1)
- Scope
- Where identifier can be referenced
- Local variable declared in block can only be used
in that block - Thats called local scope
- Class scope
- Begins at opening brace, ends at closing brace of
class - Methods and instance variables
- Can be accessed by any method in class
50Scope Rules (2)
- Block scope
- Begins at identifier's declaration, ends at
terminating brace - Local variables and parameters of methods
- When nested blocks, need unique identifier names
- If local variable has same name as instance
variable - Instance variable "hidden"
- Method scope
- For labels (used with break and continue)
- Only visible in method in which it is used
51Method Overloading
- Method overloading
- Methods with same name and different parameters
- Overloaded methods should perform similar tasks
- Method to square ints and method to square
doubles -
- public int square( int x ) return x x
- public float square( double x ) return x x
- Program calls method by signature
- Signature determined by method name and parameter
types - Overloaded methods must have different parameters
- Return type cannot distinguish method
52Arrays
- Array
- Group of consecutive memory locations
- Same name and type
- Static(Remain same size)
- To refer to an element, specify
- Array name and Position number (index)
- Format
- arraynameposition number
- First element at position (index) 0
- Every array knows its own length c.length
53Declaring/Allocating Arrays
- Declaring arrays
- Specify type, use new operator
- Place brackets after array reference variable
name in declaration - Allocate memory for actual array object
- Specify number of elements in allocation
- Two steps
- int c //declaration
- c new int 12 //allocation
- Or one step
- int c new int 12
- Primitive elements are initialized to zero or
false while Non-primitive references are
initialized to null
54References and Reference Parameters
- Passing arguments to methods
- Call-by-value pass copy of argument
- Call-by-reference pass original argument
- Pass-by-reference improves performance but
weakens security - In Java, you cannot choose how to pass arguments
- Primitive data types passed call-by-value
- References to objects passed call-by-reference
- Original object can be changed in method
- Arrays in Java treated as objects
- Passed call-by-reference
55Passing Arrays to Functions
- Passing arrays
- Specify array name without brackets
- int myArray 24
- myFunction( myArray )
- Arrays passed call-by-reference
- Modifies original memory locations
- Header for method modifyArray might be
- void modifyArray( int b )
- Passing array elements
- Passed by call-by-value
- Pass subscripted name (i.e., myArray3) to method
56Multiple-Subscripted Arrays
- Represent tables
- Arranged by m rows and n columns (m by n array)
- Can have more than two subscripts
- Array of arrays
- Fixed rows and columns
- arrayType arrayName new arrayType
numRows numColumns int b new int 3
3 - Initializer lists
- arrayType arrayName row1 sub-list,
row2 sub-list, ... - int b 1, 2 , 3, 4
- Can have variable rows and columns, too (ragged
arrays)
57Java Applets
- Java applets are programs that run on a java
enabled browser. - Java applets do not have main methods.
- Use init() and paint() instead of main() or
constructors - To compile your program, use command c\gt
javac MyAppletName.java - To run your program, use command c\gt
appletviewer my_html.html - Applet Development Process
- Step 1 Write the applet program
- Step 2 compile .java file and get .class file
- Step 3 create HTML file
- Step 4 test the applet using appletviewer
- Step 5 Publish the applet
58What can an applet do?
- Applets can use almost all java API capabilities.
- Applets have a great graphical capabilities.
- Applets can play sounds.
- Applets make the web page extremely interactive
- Applets can usually make network connections to
the host they came from. - Applets can interact with other applets on the
same page.
59What can an applet not do?
- An applet cannot load libraries or define native
methods. - It cannot read or write files on the host that's
executing it. - It cannot read certain system properties.
- It cannot make network connections except to the
host that it came from. - It cannot start any program on the host that's
executing it. - Windows that an applet brings up look different
than windows that an application brings up.
60HTML Applet Tag
- ltHTMLgt
- lt APPLET
- CODE appletFile
- WIDTH pixels
- HEIGHT pixels
- gt
- lt/APPLETgt
- lt/HTMLgt
61Part 3
- Java Implementation of the OOP Model
62Introduction
- Java is a full object-oriented programming
language. - The class is the unit of Java programming. Java
supports - Classes
- Inner classes
- Anonymous classes
- Abstract Classes
- Interfaces
- Java OOP is build on the single rooted hierarchy
which means that all classes should be inherited
from a single base class. In Java the name of
this ultimate base class is simply Object. - A class in Java represent a data type that
Encapsulates data (attributes) and methods
(behaviors) that are closely related.
63Creating Packages (1)
- Packages
- Directory structures that organize classes and
interfaces - Mechanism for software reuse
- Creating packages
- Create a public class
- If not public, can only be used by classes in
same package - Choose a package name and add a package statement
to source code file - Compile class (placed into appropriate directory)
- Use Java standards in naming the packages.
64Creating Packages (2)
- import
- Use import when classes are not of same package.
- If no package specified for a class, it is put in
the default package which includes compiled
classes of the current directory - If class in same package as another, import not
required - Follow these steps to create a package
- Create a directory called classes inside
directory c\jdk1.2\jre\ - Use the following command for compilation
- javac d c\jdk1.2\jre\classes MyClasse.java
- Once the package has been created you can use
import statement to use its classes.
65Creating Java Classes (1)
- A class in Java is just a blueprint telling what
the objects created from it will look and act
like. - Every class in Java is a subclass of the ultimate
base class Object - Every Class has three components
- Instance variables (Class Attributes).
- Member methods (Class Behavior)
- Constructors. ( For initialization and
consistency) - A class has a header (or heading) and a body
- Class body is delineated by braces
66Creating Java Classes (2)
67Class Declarations
- For class declaration, we use one or more of the
following - public the class can be used by any class
regardless of its package. - abstract the class cannot be instantiated.
- final that the class cannot be subclassed.
- class NameOfClass to indicate to the compiler
that this is a class declaration and that the
name of the class is NameOfClass. - extends Super to identify Super as the
superclass of the class. - implements Interfaces to declare that the class
implements one or more interfaces. - Body defined within
68Class Constructors
- All Java classes have constructors that are used
to initialize a new object of that type. - A constructor has the same name as the class.
Example - public Stack()
- items new Vector(10)
-
- Java supports name overloading for constructors
so that a class can have any number of
constructors. Example - public Stack(int initialSize)
- items new Vector(initialSize)
-
- The compiler differentiates these constructors
based on the number of parameters in the list and
their types. - Constructors cannot return values. There is no
return type, not even void.
69Declaring Member Variables
- Member variables represent the state of the
object. - They should be initialized in some way when
creating the object to make sure that the object
is in a consistent state. - We use modifiers when declaring Member variables.
70Method Declaration
- Methods are the ways through which objects
communicate with each other - A method's declaration provides a lot of
information about the method to the compiler, to
the runtime system, and to other classes and
objects - We use modifiers when declaring Methods.
71Methods Overriding
- Overriding a method in a subclass means
re-writing or modifying its code so that it acts
differently from what it used to. - Method overriding is related to a very important
feature of OOP known as polymorphism - Example Overriding methods init() or paint() in
applets.
72Class Inheritance Polymorphism
- Inheritance
- Constructing one class from another
- E.g., constructing a Sphere from a Circle
class - Polymorphism
- Provides the ability to redefine how methods of
related classes operate based on the object being
referenced
73Managing Inheritance (1)
- Inheritance is a form of software reusability
where - New classes created from existing ones
- Subclasses absorb super-classes attributes and
behaviours - Subclasses also add in their own attributes and
behaviours - The Object class defines and implements behavior
that every class in the Java system needs. - The following will be the hierarchy that every
class in Java will end up part of.
74Managing Inheritance (2)
- What Members Does a Subclass Inherit?
- Subclasses inherit those superclass members
declared as public or protected. - Subclasses inherit those superclass members
declared with no access specifier as long as the
subclass is in the same package as the
superclass. - Subclasses don't inherit a superclass's member if
the subclass declares a member with the same
name. - Hiding Member Variables
- Member variables defined in the subclass hide
member variables that have the same name in the
superclass. While this feature of the Java
language is powerful and convenient, it can be a
fruitful source of errors. - Overriding Methods
- The ability of a subclass to override a method in
its superclass allows a class to inherit from a
superclass whose behavior is "close enough" and
then supplement or modify the behavior of that
superclass.
75Managing Inheritance (3)
- A Subclass is more specific than a superclass
- Every subclass can be described by its
superclass, but not vice-versa - Unlike C, Java does not support multiple
inheritance. - To inherit from a class use keyword extends
- class TwoDimensionalShape extends Shape
- ...
- Inheritance does also apply to Java interfaces.
76Derived Class Properties
- Derived class
- Derived from base
- Also called
- Child or Subclass
- Completely new class
- Incorporates all the variables and methods of the
base class - Adds new data and method members
- Can override any base class method
77Polymorphism
- Permits the same method name to invoke
- One response in objects of a base class
- Another response in objects of a derived class
- The determination of which overloaded method is
actually called is made at run time - Known as run-time binding
- Object being operated on ultimately determines
the appropriate method to be called
78Overriding or Overloading Polymorphism?
- Polymorphism translates from Greek as many forms
( poly many, morph - forms) - Method overloading is the primary way
polymorphism is implemented in Java - Overloaded methods appear in a subclass with same
name but different parameter lists and return
types - Late-binding (or run-time binding) also supports
overriding - Overriding allows a subclass to re-define a
method it inherits from it's superclass - An over-ridden method in a subclass has the same
signature (name and parameter list) and also the
same return type (different from C!)
79Kinds of Inheritance
- Simple inheritance
- Each derived type has only one immediate base
type - Multiple inheritance
- Derived type has two or more base types
- Not supported in Java
- Class hierarchies
- Illustrate the order in which one class is
derived from another
80Being a Descendent of Object (1)
- The Object class sits at the top of the class
hierarchy tree in the Java platform. This class
defines the basic state and behavior that all
objects must have. - Your classes may want to override the following
Object methods - clone - equals/hashCode - finalize - toString
- Your class cannot override these Object methods
- getClass - notify - notifyAll - wait
81Being a Descendent of Object (2)
- The clone MethodYou use the clone method to
create an object from an existing object. - The finalize Method The Object class provides a
method, finalize, that cleans up an object before
it is garbage collected. - The toString Method Object's toString method
returns a String representation of the object. - The getClass Method The getClass method is a
final method that returns a runtime
representation of the class of an object. - Your class cannot override these Object methods
- getClass - notify - notifyAll - wait
82Controlling Access to Class Members (1)
- In Java, you can use access specifiers to protect
both a class's variables and its methods when you
declare them. - The Java language supports four distinct access
levels for member variables and methods private,
protected, public, and, if left unspecified,
package. - Private
- The most restrictive access level is private.
- A private member is accessible only to the class
in which it is defined. Inheritance does not
apply on the private members. They are Just like
secrets. - Use private keyword to create private members.
83Controlling Access to Class Members (2)
- Protected
- Allows the class itself, subclasses, and all
classes in the same package to access the
members. - Use the protected access level when it's
appropriate for a class's subclasses to have
access to the member, but not unrelated classes.
Protected members are like family secrets. - To declare a protected member, use the keyword
protected
84Controlling Access to Class Members (3)
- Public
- The easiest access specifier is public.
- Any class, in any package, has access to a
class's public members. - Declare public members only if such access cannot
produce undesirable results if an outsider uses
them. - There are no personal or family secrets here
this is for stuff you don't mind anybody else
knowing. - To declare a public member, use the keyword
public.
85Controlling Access to Class Members (4)
- Package
- The package access level is what you get if you
don't explicitly set a member's access to one of
the other levels. - This access level allows classes in the same
package as your class to access the members. This
level of access assumes that classes in the same
package are trusted friends. - To summarize
86Class Scope
- Class scope
- Includes Instance variables and methods
- Class members are accessible to class methods.
They can be referenced simply by name. - Outside scope, cannot be referenced by name
- Visible (public) members accessed through a
handle - objectReferenceName.variableName or .methodName()
- Static public members can be accessed through
class name like - Color.red, Font.PLAIN, System.out.print()
- Block scope
- Variables defined in a method known only to that
method - If variable has same name as class variable,
class variable is hidden in that method.
87final Variables, Methods, and Classes
- Declaring variables final
- Indicates they cannot be modified after
declaration - Indicate that they are constants
- Must be initialized when declared. Can not be
changed after that - Use all-caps identifiers. Example
- private final int INCREMENT 5
- Declaring methods final
- Cannot be overridden in a subclass
- static and private methods are implicitly final
- You can only hide a static method
- Static means one per class, not one for each
object no matter how many instance of a class
might exist. This means that you can use them
without creating an instance of a class.Static
methods are implicitly final, because overriding
is done based on the type of the object, and
static methods are attached to a class, not an
object. A static method in a superclass can be
shadowed by another static method in a subclass,
as long as the original method was not declared
final. However, you can't override a static
method with a nonstatic method. In other words,
you can't change a static method into an instance
method in a subclass. - Declaring classes final
- Cannot be a super-class (cannot inherit from it)
- All methods in class are implicitly final
88Static Class Members (1)
- Static variables
- Class data members are divided into two groups
- Instance variables every object of the class has
its own copies of them. - Class variables they are allocated once for the
class. - All objects of class share the same class
variable. - Keyword static is used to create class variables.
- static class variables shared among all objects
of class - One copy for entire class to use
- static class variables exist even when no objects
do - public static members
- Accessed through references or class name and dot
operator - MyClass.myStaticVariable
- private static members
- Accessed through class methods.
89Static Class Members (2)
- static methods
- Can only access static members
- Have no this reference
- static variables are independent of objects
- They can be called even if no object is created.
- Examples
- The main method in public static void
main(String args) - Method exit() in System.exit()
- Method showMessageDialog() in JOptionPane.showMess
ageDialog(. . .)
90Initializing Objects
- Initialization is a must every time an object is
created out of a class. - Java compiler will initialize all class members
and creating default constructors that initialize
data members as follows 0 for primitive numeric
types, false for boolean, null for references. - Initialization mainly happened in the class
constructors. - A class could have more than one way
(constructor) of initialization. - Initializers are passed as arguments to
constructor
91Object Instantiating
- Classes only describe data types. To put then in
use at runtime, objects have to be created
(instantiated) from them. - new keyword is used to instantiate an object
from a class. Example - public Font myFnt new
- Font(Arial, Font.ITALIC, 12)
- No objects can be instantiated from Abstract
classes. You can not use new here.
92Composition
- Composition means that a class has references to
other objects as members - These objects have to be initialized.
- Default constructor or available constructors are
used to initialize these objects. - Composition is a powerful way of software re-use
- Composition is related to the has a
relationship in the OOP model.
93Using this Reference
- Each object has a reference to itself . It is
called this reference - Implicitly used to refer to instance variables
and methods - Used inside methods
- If a parameter or a local variable has the same
name as an instance variable, use
this.variableName to explicitly refer to the
instance variable. Use variableName to refer to
the parameter - It helps clarify the program logic.
94Abstract Classes
- Sometimes, a class that you define represents an
abstract concept and, as such, should not be
instantiated. - For example, the Number class in the java.lang
package represents the abstract concept of
numbers. Number class makes sense only as a
superclass to classes like Integer or Float. - An abstract class is a class that can only be
subclassed-- it cannot be instantiated. - To declare that your class is an abstract class,
use the keyword abstract before the class keyword
in your class declaration - abstract class Number . . .
- An abstract class may contain abstract methods,
that is, methods with no implementation. In this
way, an abstract class can define a complete
programming interface, thereby providing its
subclasses with the method declarations for all
of the methods necessary to implement that
programming interface.
95Abstract methods cannot be
- Abstract methods cannot be declared as
- static or final
- final not allowed because it doesnt allow
over-riding by definition - static because you can only hide a static
method - Static means one per class, not one for each
object no matter how many instance of a class
might exist. This means that you can use them
without creating an instance of a class.Static
methods are implicitly final, because overriding
is done based on the type of the object, and
static methods are attached to a class, not an
object. A static method in a superclass can be
shadowed by another static method in a subclass,
as long as the original method was not declared
final. However, you can't override a static
method with a nonstatic method. In other words,
you can't change a static method into an instance
method in a subclass.
96Inner Classes
- Inner classes are classes defined inside other
classes. - Inner classes have access to all the members of
the outer classes. - Usually we use inner classes as helper classes of
adapter classes. - Inner classes can be anonymous (without names)
- They are used intensively to write event
listeners such as ActionListener, MouseListener,
KeyListener, and the like.
97Abstract Classes and Interfaces
- Abstract class
- Can only be used as a base class for another
class - Can not be instantiated
- Created using the abstract reserved word in the
class header - Typically contains one or more abstract methods
- Method does not contain a body, only a header
- Derived classes must define abstract method
implementation - Class can also include non-abstract methods
98Interfaces
- An Interface consists of constants and abstract
methods only - Syntax
- interface interfaceName
- constant declarations
- abstract method declarations
99Interfaces (continued)
- Interface
- Methods must be public and abstract
- Constants must be public and final
- No need to actually use these modifiers in method
and constant definitions since theyre understood
for an interface!
100Implementing an interface
- Implementing an interface syntax
- class className implements interfaceName
override defns of all abstract methods
101Java Interfaces (1)
- An interface defines a protocol of behavior that
can be implemented by any class anywhere in the
class hierarchy. - An interface defines a set of methods but does
not implement them. A class that implements the
interface agrees to implement all the methods
defined in the interface, thereby agreeing to
certain behavior. - An interface is not part of the class hierarchy.
Unrelated classes can implement the same
interface. - Two elements are required in an interface
declaration--the interface keyword and the name
of the interface. - The public access specifier indicates that the
interface can be used by any class in any
package.
102Java Interfaces (2)
- An interface can inherit from one or more
comma-separated superinterfaces using keyword
extends. - The interface body contains method declarations
each followed by a semicolon (). All methods
declared in an interface are implicitly public
and abstract. - An interface can also contain constant
declarations. All constant values defined in an
interface are implicitly public, static, and
final.
103Implementing an Interface
- An interface defines a protocol of behavior. A
class that implements an interface adheres to the
protocol defined by that interface. - To declare a class that implements an interface,
include an implements clause in the class
declaration. - Your class can implement more than one interface
(the Java platform supports multiple inheritance
for interfaces. For instance, - public class StockApplet extends Applet
- implements StockWatcher
- public void valueChanged(String
- tickerSymbol, double newValue)
-
104Simulated Multiple Inheritance
- Since Java does not support direct multiple
inheritance, it provides an alternate mechanism
to allow for the full power of multiple
inheritance - This is via implementation of multiple
interfaces, as needed - This also supports polymorphism (with run-time
binding) as an interface reference variable (but
NOT an interface object as you CANNOT instantiate
interfaces) can point to an object of any
descendant class that implements that interface - The methods of the interface are over-ridden in
the descendant classes that implement that
interface
105Part 4
106UML Diagram Types
- Class
- Object
- State
- Sequence
- Activity
- Use-case
- Component
- Deployment
- Collaboration
107(No Transcript)
108Objects
- Objects have three responsibilities
- What they know about themselves (e.g.,
Attributes) - What they do (e.g., Operations)
- What they know about other objects (e.g.,
Relationships)
109Defining Class
A CLASS is a template (specification,
blueprint) for a collection of objects that share
a common set of attributes and operations.
HealthClubMember
attributes operations
Class Objects
110Relationships
- The three basic relationships include
- Association (between objects) relationships
that are described as has-a - Aggregation (between objects) composed-of
(strong aggregation/composition) and
consists-of (weak aggregation) - Aggregations (weak and strong/composition) are
considered a more tightly coupled type of
association and also have the same
multiplicities/cardinalities - Generalization (between classes) is-a
111A RELATIONSHIP is what a class or an object knows
about another class or object.
- Generalization (Class-to-Class)
(Superclass/Subclass) - Inheritance
- Ex Person - FacultyPerson, StudentPerson,
Staff... - Ex ModesOfTravel - Airplane, Train, Auto,
Cycle, Boat... - Object Associations
- FacultyInformation - CourseInformation
- StudentInformation - CourseInformation
- Object Aggregations Composition (Whole-Part)
- Assembly - Parts
- Group - Members
- Container - Contents
F o u r T y p e s in Three Classes
112(No Transcript)
113(No Transcript)
114(No Transcript)
115Java Programming Styles (1)
- Packages
- Package names are entirely in lower case.
- Package name should start with the web domain
name reversed - Examples
- package com.sun.java.lang
- package edu.nmsu.is.us.sp
- Files
- The file name must have the same base name as the
name of the public class defined in the file. - Example
- If you have a public class named RecordList,
the file containing this class should be named
RecordList.java
116Java Programming Styles (2)
- Classes and Interfaces
- Use meaningful identifiers for classes , and
interfaces. - Capitalize each word contained in a class
identifier name. - No underscores.
- Examples
- public class RecordList
- public interface PanelFace
117Java Programming Styles (3)
- Variables
- Use meaningful identifiers for variables.
- Capitalize each word contained in a name of a
variable except the first word. - Use nouns to identify variables as possible.
- For boolean variables, use identifirs that are
like questions. - Use all-caps indentifiers for constants.
- Examples
- int number
- String myName
- boolean isValid
- final int CODE 707
118Java Programming Styles (4)
- Methods
- Use meaningful identifiers for methods.
- Capitalize each word contained in a name of a
method except the first word. - Use verbs to identify methods as possible.
- For the methods dealing with objects properties,
start the method identifier with get or set. - If the method returns boolean use is or are
instead of get to name this method. - Examples
- private boolean paint()
- boolean isObjectValid()
- Font getFont()
- void setFont(Font f)
119Java Programming Styles (5)
- General Considerations
- Use three-space indentation style. Example
- if(num lt 10)
-
- System.out.println(Not Enough)
-
- Use comments to mark the beginning and the end of
blocks - Use three-line style to comment your code. Use
either one of - // /
- // This part is to or This part is to
- // /
- Use empty lines to increase the readability of
your code - Use spaces between the operators such as , -, ,
and the operands. Example - c a b
120Software Reusability Issues
- Software
- Constructed from existing, well-defined,
carefully tested, portable, widely available
components - Speeds development of powerful, high-quality
software - Use library classes as much as you can
- Never re-invent the wheel
- Organize your code so that you can use it again.
- Apply principle of least privilege
- Each component has enough access to accomplish
its task, nothing more - Prevents accidental/malicious errors
121Using Set and Get Methods
- Set methods (Mutator methods)
- public method that sets private variables
- Does not violate notion of private data
- Change only the variables you want
- Called mutator methods (change value)
- Get methods (Accessor methods)
- public method that displays private variables
- Again, does not violate notion of private data
- Only display information you want to display
- Also called accessor or query methods
- If implementation changes
- Clients can still use the same methods
- Do not know implementation details
122Documentation Generator
- Java has its own standard tool for creating API
documentation on the fly. This tool is javadoc. - javadoc goes through the source files looking for
a comment of the style / / to add to the
documentation. - The result of the javadoc utility is HTML
documentation that is the same as the Java
standard API documentation in format.
123Part 5
124AWT to Swing
- AWT Abstract Windowing Toolkit
- import java.awt.
- Swing new with Java2
- import javax.swing.
- Extends AWT
- Tons o new improved components
- Standard dialog boxes, tooltips,
- Look-and-feel, skins
- Event listeners
- API
- http//java.sun.com/j2se/1.3/docs/api/index.html
125GUI Component API
- Java GUI component class
- Properties
- Methods
- Events
JButton
126Using a GUI Component
- Declare it
- Declare object JButton b
- Create it
- Instantiate object b new JButton(press
me) - Configure it
- Methods b.setText(press me)
- Add it
- contentPane.add(b)
- Listen to it
- Events Add Listeners for its events!
JButton
127Anatomy of an Application GUI
GUI
Internal structure
JFrame
JFrame
JPanel
containers
JPanel
JButton
JButton
JLabel
JLabel
128Using a GUI Component 2
- Create it
- Configure it
- Add children (if container)
- Add to parent (if not JFrame)
- Listen to it
order isimportant
129Build from bottom up
Listener
- Create (bottom-up)
- Frame
- Panel
- Components their Listeners
- Add (top-down)
- listeners into components
- components into panel
- p