LQAS-JAVA-OOP-More
-
Upload
taras-lytvyn -
Category
Documents
-
view
217 -
download
0
Transcript of LQAS-JAVA-OOP-More
-
7/28/2019 LQAS-JAVA-OOP-More
1/26
2010 Marty Hall
Ob ect-OrientedProgramming in Java:
Originals of Slides and Source Code for Examples:
-
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite atyourlocation.2
. . .
2010 Marty Hall
For live Java EE training, please see training courses
at htt ://courses.coreservlets.com/.Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo,Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT),
Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,Hibernate/JPA, and customized combinations of topics.
Taught by the author ofCore Servlets and JSP, More
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite atyourlocation.
, .venues, or customized versions can be held on-site at your
organization. Contact [email protected] for details.
-
7/28/2019 LQAS-JAVA-OOP-More
2/26
Agenda
Overloading
Best practices for real classesEncapsulation and accessor methods
ava oc
Inheritance
Abstract classes
CLASSPATH
PackagesVisibility modifiers
JavaDoc options4
2010 Marty Hall
Overloading
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite atyourlocation.5
-
7/28/2019 LQAS-JAVA-OOP-More
3/26
Overview
IdeaClasses can have more than one method with the same
name, or more than one constructor.
other by having different number or types of arguments
Syntaxpublic class MyClass {
public double getRandomNum() { }; // Range 1-10
}
MotivationMethods: lets you have similar names for similar ops
Constructors: let you build instances in different ways6
Ship Example: Overloadingpublic class Ship4 { (In Ship4.java)public double x=0.0, y=0.0, speed=1.0, direction=0.0;public String name;
public Ship4(double x, double y,double speed, double direction,String name) {
this.x = x;this.y = y;
this.speed = speed;this.direction = direction;this.name = name;
}
public Ship4(String name) {this.name = name;
}
private double degreesToRadians(double degrees) {return(degrees * Math.PI / 180.0);
}
...7
-
7/28/2019 LQAS-JAVA-OOP-More
4/26
Overloading (Continued)
...
public voidmove() {
move(1);}
public voidmove(int steps) {
double an le = de reesToRadians(direction);
x = x + steps * speed * Math.cos(angle);
y = y + steps * speed * Math.sin(angle);
}
public void printLocation() {
System.out.println(name + " is at ("
+ x + "," + y + ").");
}
}8
Overloading: Testing and
public class Test4 { (In Test4.java)
ublic static void main Strin ar s
Ship4 s1 = new Ship4("Ship1");
Ship4 s2 = new Ship4(0.0, 0.0, 2.0, 135.0, "Ship2");
s1.move();
s2.move(3);
s1.printLocation();
s2.printLocation();
}
- ,DOS> javac Test4.java
DOS> java Test4
Ship1 is at (1.0,0.0).
Ship2 is at (-4.24264...,4.24264...).
9
-
7/28/2019 LQAS-JAVA-OOP-More
5/26
Overloading: Major Points
Idea ows you o e ne more an one unc on or
constructor with the same name Overloaded functions or constructors must differ in the
,can always tell which one you mean
Simple examples:
type of the argument; they would both be permitted insidethe same class definition.
// square(4) is 16public int square(int x) { return(x*x); }
square our s our ourpublic String square(String s) {
return(s + " " + s);}10
2010 Marty Hall
Best Practices
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite atyourlocation.11
-
7/28/2019 LQAS-JAVA-OOP-More
6/26
Overview
Ideas Instance variables should always be private
And hooked to outside world with getBlah and/or setBlah -,
Syntax/** Short summary. More detail. Can use HTML. */
public class MyClass {
private String firstName;
ublic Strin etFirstName return firstName
public void setFirstName(String s) { firstName = s; }
} o va on
Limits ripple effect. Makes code more maintainable.12
Ship Example: OOP Design and
/** Ship example to demonstrate OOP in Java. */
public class Ship {
private double x=0.0, y=0.0, speed=1.0, direction=0.0;
private String name;
/** Get current X location. */
public double getX() {
return(x);
}
/** Set current X location. */
this.x = x;
}13
-
7/28/2019 LQAS-JAVA-OOP-More
7/26
OOP Design: Testing and
public class ShipTest { (In ShipTest.java)
ublic static void main Strin ar s
Ship s1 = new Ship("Ship1");
Ship s2 = new Ship(0.0, 0.0, 2.0, 135.0, "Ship2");s1.move();
s2.move(3);
s1.printLocation();
s2.printLocation();
}
- ,javac ShipTest.java
java ShipTest
javadoc *.java
Output:Ship1 is at (1.0,0.0).
Ship2 is at (-4.24264...,4.24264...).14
OOP Design: Testing and Results
15
-
7/28/2019 LQAS-JAVA-OOP-More
8/26
Major Points
EncapsulationLets you change internal representation and data
structures without users of your class changing their code
class changing their code
Lets you perform arbitrary side effects without users ofyour class changing their code
Comments and JavaDoc ommen s mar e w ... w e par o e
online documentation
Call "javadoc *.java" to build online documentation.
See later slides for details
16
More Details on Getters and
Eclipse will automatically buildgetters/setters from instance variablesR-click anywhere in code
However, if you later click on instance variable and do
Refactor Rename, Eclipse will not automaticallyrename the accessor methods
17
-
7/28/2019 LQAS-JAVA-OOP-More
9/26
More Details on Getters and
There need not be both getters and setters It is common to have fields that can be set at instantiation,
but never changed again (immutable field). It is evenuite common to have classes containin onl immutable
fields (immutable classes)
private final String name;
pu c p name = ;
public String getName() { return(name); }
// No setName method18
More Details on Getters and
Getter/setter names need not correspond toinstance variable namesCommon to do so if there is a simple correspondence, but
In fact, there doesnt even have to be a corresponding
instance variable
public class Customer {
public String getFirstName() { getFromDatabase(); }
public void setFirstName() { storeInDatabase(); }
.
}
19
-
7/28/2019 LQAS-JAVA-OOP-More
10/26
2010 Marty Hall
Inheritance
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite atyourlocation.20
Overview
Ideas ou can ma e a c ass t at n er ts c aracter st cs o
another class The original class is called parent class, super class, or
. ,subclass, or extended class.
The child class has access to all non-private methods of.
No special syntax need to call inherited methods
Syntaxpublic String ChildClass extends ParentClass { }
Motivation . .,
the same code twice). Design class hierarchies so thatshared behavior is in inherited to all classes that need it.
21
-
7/28/2019 LQAS-JAVA-OOP-More
11/26
Simple Example
Personpublic class Person {
public String getFirstName() { }public String getLastName() { }
}
public class Employee extends Person {
public double getSalary() { }
public String getEmployeeInfo() {
return(getFirstName() + " " + getLastName() +earns ge a ary ;
}
}22
Ship Example: Inheritancepublic class Speedboat extends Ship {private String color = "red";
public Speedboat(String name) {super(name);setSpeed(20);
}
public Speedboat(double x, double y,
double speed, double direction,String name, String color) {
super(x, y, speed, direction, name);setColor(color);
}
public voidprintLocation() {System.out.print(getColor().toUpperCase() + " ");super.printLocation();
}
...
}23
-
7/28/2019 LQAS-JAVA-OOP-More
12/26
Inheritance Example: Testing
public class SpeedboatTest {
Speedboat s1 = new Speedboat("Speedboat1");
Speedboat s2 = new Speedboat(0.0, 0.0, 2.0, 135.0,"Speedboat2", "blue");
Ship s3 = new Ship(0.0, 0.0, 2.0, 135.0, "Ship1");
s1.move();
s2.move();
s3.move();
s1.printLocation();
s2.printLocation();
s .pr n oca on ;
}
}
24
Inheritance Example: Result
Compiling and running in EclipseSave SpeedBoatTest.java
R-click, Run As Java Application
DOS> javac SpeedboatTest.java
The above calls javac on Speedboat.java and Ship.javaautomatically
DOS> java SpeedboatTest
u puRED Speedboat1 is at (20,0).
BLUE S eedboat2 is at (-1.41421,1.41421).
Ship1 is at (-1.41421,1.41421).
25
-
7/28/2019 LQAS-JAVA-OOP-More
13/26
Ship Inheritance Example:
Format for defining subclasses
Using inherited methods
Using super() for inherited constructorsOnly when the zero-arg constructor is not OK
Using super.someMethod() for inherited
Only when there is a name conflict
26
Inheritance Syntax for defining subclasses
...
}
Nomenclature: The old class is called the superclass,base class orparent class The new class is called the subclass, derived class orchild class
Effect of inheritance Subclasses automatically have all public fields and methods of theparent class
You dont need any special syntax to access the inherited fields and
fields or methods. You can also add in fields or methods not available in the superclass
A class can only have one directparent. But grandparent and great-
grandparent (etc.) are legal and common.27
-
7/28/2019 LQAS-JAVA-OOP-More
14/26
Inherited constructors and...
When you instantiate an object of a subclass, thesys em w au oma ca y ca e superc ass
constructor first By default, the zero-argument superclass constructor is called If you want to specify that a different parent constructor is called,
invoke the parent class constructor with super(args)
Ifsuper() is used in a subclass constructor, then super()must be the first statement in the constructor
Constructor life-cycle
1. Invoke the constructor of the superclass
The zero-argument constructor is called automatically. No special syntaxis needed unless you want a different parent constructor.
2. Initialize all instance variables based on their initializationstatements
3. Execute the body of the constructor28
Overridden methods and. ...
When a class defines a method using the, ,
method in the superclass, then the classoverrides the method in the superclass
-
If there is a locally defined method and ann er e me o a ave e same nameand take the same arguments, you can use thefollowing to refer to the inherited method
super.methodName(...)
Successive use ofsu er su er.su er.methodName isnot legal.
29
-
7/28/2019 LQAS-JAVA-OOP-More
15/26
2010 Marty Hall
Advanced Topics
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite atyourlocation.30
Advanced OOP Topics
Abstract classes
Interfaces
CLASSPATH
Packages
Visibility other than public or private JavaDoc details
31
-
7/28/2019 LQAS-JAVA-OOP-More
16/26
Abstract Classes
IdeaA class that you cannot directly instantiate (i.e., on which
you cannot use new). But you can subclass it andinstantiate the subclasses.
Syntaxpublic abstract class SomeClass {
public abstract SomeType method1(); // No body
public SomeType method2() { } // Not abstract
Motivation Lets you make collections of mixed types
32
Abstract Classes: Problem
You haveCircle and Rectangle classes, each with getArea methods
Goal et sum o areas o an array o rc es an ectang es
Object[] shapes =
{ new Circle(), new Rectangle() };
double sum = 0;
for(Object shape: shapes) {
sum = sum + shape.getArea();
33
-
7/28/2019 LQAS-JAVA-OOP-More
17/26
Abstract Classes: Solution
Shapepublic abstract class Shape {
public abstract double getArea();
public void printInfo() {
System.out.println(getClass().getSimpleName() +
" has area " + getArea());
}
}
Circle and similar for Rectan lepublic class Circle extends Shape {
public double getArea() { }
}
34
Interfaces
IdeaA model for a class. More or less an abstract class but
without any concrete methods.
public interface SomeInterface {
public SomeType method1(); // No bodypublic SomeType method2(); // No body
}
public class SomeClass implements SomeInterface {
// Real definitions of method1 and method 2
}
Like abstract classes, guarantees classes have certain
methods. But classes can implement multiple interfaces.35
-
7/28/2019 LQAS-JAVA-OOP-More
18/26
Interfaces: Problem
Sum of areasYou again want to get sum of areas of mixture of Circles
and Rectangles. ,
concrete printInfo method
Why interface instead of abstract class?Classes can directly extend only one class (abstract or
otherwise)
public class Foo extends Bar implements Baz, Boo {
36
Interfaces: Solution
Shapepublic interface Shape {
public double getArea();
}
Circlepublic class Circle implements Shape {
ublic double etArea }
Rectanglepu c c ass ec ang e mp emen s ape
public double getArea() { }
}
37
-
7/28/2019 LQAS-JAVA-OOP-More
19/26
CLASSPATH
IdeaThe CLASSPATH environment variable defines a list of
directories in which to look for classes =
Best practice is to not set this when first learning Java!
Setting the CLASSPATHset CLASSPATH = .;C:\java;D:\cwp\echoserver.jar
setenv CLASSPATH .:~/java:/home/cwp/classes/
.
Supplying a CLASSPATHjavac classpath .;D:\cwp WebClient.java
java classpath .;D:\cwpWebClient
38
Packages
Idea Organize classes in groups.
Syntax
Make folder called somePackage (in Eclipse, R-click on srcand do New Package)
To use code from another package put import somePackage.* in file below your package
Motivation You only have to worry about name conflicts within your
pac age. So, team members can work on different parts of project without
worrying about what class names the other teams use.39
-
7/28/2019 LQAS-JAVA-OOP-More
20/26
Visibility Modifiers
publicThis modifier indicates that the variable or method can be
accessed anywhere an instance of the class is accessible ,
that any other class can use the class definition
The name of a public class must match the filename, thusa file can have only one public class
private
methods within the same class
Declare allinstance variables private
Declare methods private if they are not part of classcontract and are just internal implementation helpers
40
Visibility Modifiers (Continued)
protectedProtected variables or methods can only be accessed by
methods within the class, within classes in the sameacka e and within subclasses
[default]
Default visibility indicates that the variable or method canbe accessed by methods within the class, and withinclasses in the same package
omitted . Rarely used!
private: very common. Use this as first choice.
pu c: common or me o s an cons ruc ors. n c o ce
protected: usually for instance vars only. Moderately rare.
default: very rare. Dont omit modifier without good reason.41
-
7/28/2019 LQAS-JAVA-OOP-More
21/26
Visibility Summary
Modifiers
Accessible from same class? yes yes yes yes
Accessible to classes (nonsubclass) yes yes yes no
Accessible to subclass from the yes yes yes no
same package?
Accessible to classes (nonsubclass) yes no no no
from differentpackage?
Accessible to from es no no no
different package?
Inherited by subclass in the yes yes yes nosame package?
42
Inherited by subclass in different yes yes no no
package?
Other Modifiers
final or a var a e: canno e c ange a er ns an a on
Widely used to make immutable classes
For a class: cannot be subclassed
For a method: cannot be overridden in subclasses
synchronized
Only one thread can access the code at any given time
volatileGuarantees other threads see changes to variable
transient
native Indicates that the method is implement using C or C++43
-
7/28/2019 LQAS-JAVA-OOP-More
22/26
Comments and JavaDoc
Java supports 3 types of comments // Comment to end of line.
/* Block comment containing multiple lines.*.
/** A JavaDoc comment placed before classdefinition and nonprivate methods.Text may contain (most) HTML tags,hyperlinks, and JavaDoc tags. */
Used to generate on-line documentation
javadoc Foo.java Bar.java (or *.java)
JavaDoc Home Page http://java.sun.com/javase/6/docs/technotes/tools/windows/javadoc.html
44
Useful JavaDoc Tags
@author pec es e au or o e ocumenMust use javadoc author ... to generate in output
/** Description of some class ...** @author * Marty Hall*/
Version number of the documentMust use javadoc version ... to generate in output
@param Documents a method argument
Documents the return type of a method
45
-
7/28/2019 LQAS-JAVA-OOP-More
23/26
Useful JavaDoc Command-line
-author Inc u es aut or n ormat on om tte y e au t
-version Includes version number (omitted by default)
-noindex Tells javadoc not to generate a complete index
- Tells javadoc not to generate the tree.html class hierarchy
-link, -linkoffline Tells javadoc where to look to resolve links to other packages
-link http://java.sun.com/j2se/1.5.0/docs/api/-linkoffline http://java.sun.com/j2se/1.5.0/docs/api/
c:\jdk1.5\docs\api
46
JavaDoc: Example/** Ship example to demonstrate OOP in Java.** @author* Marty Hall*/
public class Ship {private double x=0.0, y=0.0, speed=1.0, direction=0.0;private String name;
/** Build a ship with specified parameters. */
public Ship(double x, double y, double speed,double direction, String name) {
setX(x);setY(y);setSpeed(speed);setDirection(direction);setName(name);
}...
47
-
7/28/2019 LQAS-JAVA-OOP-More
24/26
JavaDoc: Example
> javadoc -link http://java.sun.com/j2se/1.5.0/docs/api/
-author *. ava
48
2010 Marty Hall
Wrap-Up
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite atyourlocation.49
-
7/28/2019 LQAS-JAVA-OOP-More
25/26
Java OOP References
Online as cs sect on o un ava utor a
http://java.sun.com/docs/books/tutorial/java/ Books
Murachs Java SE 6(Murach, Steelman, and Lowe) Excellent Java intro for beginners to Java (but not first-
time ro rammers . Ver ood OOP section.
Thinking in Java (Bruce Eckel) Perhaps not quite as good as Murachs book in general,
but possibly the best OOP coverage of any Java book.
Effective Java, 2ndEdition (Josh Bloch)
In my opinion, the best Java book ever written. Fantasticcoverage of OOP best practices. However, very advanced. Other than the OOP chapter, you wont
understand much unless you have been doing Java fulltime for atleast a year. Even experts will learn a lot from this book.
50
Summary
Overloading ou can ave mu p e me o s or cons ruc ors w e same
name. They must differ in argument signatures (number and/ortype of arguments).
Make all instance variables private
Hook them to the outside with getBlah and/or setBlah Use JavaDoc-style comments from the very beginning
Inheritance ublic class Subclass extends Su erclass Non-private methods available with no special syntax Use super() in constructor if you need non-default parent
constructor moderatel common Use super.method() if local method and inherited method
have the same name (rare!)51
-
7/28/2019 LQAS-JAVA-OOP-More
26/26
2010 Marty Hall
u
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite atyourlocation.52