+ All Categories
Home > Documents > 04 Java OOP More

04 Java OOP More

Date post: 07-Jul-2018
Category:
Upload: raghu84taduri
View: 230 times
Download: 0 times
Share this document with a friend

of 25

Transcript
  • 8/18/2019 04 Java OOP More

    1/25

    © 2015 Marty Hall

    Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Object-OrientedProgramming in Java:

    More Capabilities

    3

    Originals of slides and sou rce code for examples: http://courses.coreservlets.com/Course-Materials/java.html

     Also see Java 8 tutorial: http://www.coreservlets.com/java-8-tutorial/ and many other Java EE tutorials: http://www.coreservlets.com/Customized Java training courses (onsite or at public venues): http://courses.coreservlets.com/java-training.html

    © 2015 Marty Hall

    Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Taught by lead author of Core Servlets & JSP , co-author of Core JSF (4th Ed), & this tutor ial. Available at public venues, orcustomized versions can be held on-site at your organization.

    • Courses developed and taught by Marty Hall – JSF 2.2, PrimeFaces, servlets/JSP, Ajax, JavaScript, jQuery, Android, Java 7 or 8 programming, GWT, custom mix of topics

     – Courses available in any state or country. Maryland/DC area companies can also choose afternoon/evening courses.

    • Courses developed and taught by coreservlets.com experts (edited by Marty) – Spring MVC, Core Spring, Hibernate/JPA, Hadoop, HTML5, RESTful Web Services

    Contact [email protected] for details

    For customized Java-related training atyour organization, email [email protected] is also available for consulting and development support

  • 8/18/2019 04 Java OOP More

    2/25

    Topics in This Section

    • Overloading

    • Best practices for “ real” classes – Encapsulation and accessor methods

     –  JavaDoc

    • Inheritance

    • Packages

    • The toString method

    • More iterations of the Person class

    5

    © 2015 Marty Hall

    Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Overloading

    6

  • 8/18/2019 04 Java OOP More

    3/25

    Overview

    • Idea – Classes can have more than one method with the same

    name, or more than one constructor – The methods or constructors have to differ from each

    other by having different number or types of arguments

    • Syntax example

     public class MyClass {

     public double randomNum() { … }; / / Range 1- 10

     public double randomNum(double range) { … }}

    7

    Motivation

    • Overloading methods – Lets you have similar names for similar operations

    • MathUtils.arraySum(arrayOfInts)

    • MathUtils.arraySum(arrayOfDoubles)

    • MathUtils.log(number) // Assumes loge(number)

    • MathUtils.log(number, base) // logbase(number)

    • Overloading constructors – Lets you build instances in different ways

    • new Ship(someName) // Default x, y, speed, direction

    • new Ship(someX, someY, someSpeed, someDirection,someName)

    8

  • 8/18/2019 04 Java OOP More

    4/25

    Ship Example: Overloading(ship4/Ship.java)

     package ship4;

     public class Ship { public double x=0.0, y=0.0, speed=1.0, direction=0.0; public String name;

     public Ship(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 Ship(String name) {this.name = name;

    }...

    9

    Overloading (Continued)...

     public void move() {

     move(1);

    }

     public void move(int steps) {

    double angle = degreesToRadians(direction);x = x + steps * speed * Math.cos(angle);

    y = y + steps * speed * Math.sin(angle);

    }

    / / degr eesToRadi ans and pr i nt Locat i on as bef or e

    }

    10

  • 8/18/2019 04 Java OOP More

    5/25

    Ship Tester 

     package ship4;

     public class ShipTest {

     public static void main(String[] args) {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();

    }

    }

    11

    Overloading: Results

    • Compiling and running in Eclipse (common) –  Save Ship.java and ShipTest.java

     –  R-click inside ShipTest.java, Run As Java Application

    • Compiling and running manually (rare)

    > javac ship4\ShipTest.java> java ship4.ShipTest

    • Output:Ship1 is at (1.0,0.0).

    Ship2 is at (-4.24264...,4.24264...).

    12

  • 8/18/2019 04 Java OOP More

    6/25

    © 2015 Marty Hall

    Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    OOP Design:Best Practices

    13

    “ Always code as if the guy who ends up maintaining your c ode

    will be a violent psychopath who knows w here you live.”

     – Joh n F. Woods

    Overview

    • Ideas –  Instance variables should always be private

    •  And hooked to outside world with getBlah and/or setBlah

     – From very beginning, put in JavaDoc-style comments

    • Syntax example/** Short summary. More detail. Can use HTML. */

    public class MyClass {

    private String firstName;

    public String getFirstName() { return(firstName); }

    public void setFirstName(String s) { firstName = s; }

    }

    14

  • 8/18/2019 04 Java OOP More

    7/25

    Motivation

    • Supports secondary goal of OOP

     – Limits ripple effect, where changes to one class requires

    changes to the classes that use it, that require changes to

    the classes that use that, and so forth.

    • Lets you make changes to internal representation of

    classes without changing its public interface.

    • Makes code more maintainable.

    15

    OOP Principles

    • Basic OOP principles

     – Primary goal: avoid needing to repeat identical or almost-

    identical code

    • DRY: Don’t Repeat Yourself 

    • Code reuse

     – Secondary goal: limit ripple effect

    •  Advanced OOP principles

     – SOLID

    • http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29

    • http://williamdurand.fr/2013/07/30/from-stupid-to-solid-code/

    16

  • 8/18/2019 04 Java OOP More

    8/25

    Ship Example: OOP Design andUsage (ship5/Ship.java)

    /** 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. */

     public void setX(double x) {

    this.x = x;

    }

    ...17

    Ship Tester  package ship5;

    /** Small example to test the Ship class.

    *

    * From the

    * coreservlets.com Java tutorials.

    */

     public class ShipTest {

     public static void main(String[] args) {

    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();

    }

    }18

  • 8/18/2019 04 Java OOP More

    9/25

    Results

    • Compiling and running in Eclipse (common) –  Save Ship.java and ShipTest.java

     –  R-click inside ShipTest.java, Run As Java Application

    • Compiling and running manually (rare)> javac ship5\ShipTest.java

    > java ship5.ShipTest

    > javadoc *.java

    • Output:

    Ship1 is at (1.0,0.0).Ship2 is at (-4.24264...,4.24264...).

    19

    You can also run JavaDocfrom within Eclipse by starting at Project menu and choosing

    “Generate Javadoc”. If it asks you where javadoc.exe is located, you can find it in the bin

    folder of your Java installation (e.g., C:\Program Files\Java\jdk1.8.0_45\bin)

    OOP Design: Testing and Results(Continued)

    20

    If you run JavaDoc from within Eclipse

    (ProjectGenerate Javadoc), it puts the

    HTML in the “doc” folder under “src”.

  • 8/18/2019 04 Java OOP More

    10/25

    Major Points

    • Encapsulation

     –  Lets you change internal representation and data structures without

    users of your class changing their code –  Lets you put constraints on values without users of your class

    changing their code

     –  Lets you perform arbitrary side effects without users of your class

    changing their code

    • Comments and JavaDoc

     –  Comments marked with /** ... */ will be part of the online

    documentation

    • These should go before every public class, every public method,

    and every public constructor 

     –  To build online documentation, use “javadoc *.java” from command

    line or, within Eclipse, do Project Generate Javadoc21

    More Details on Getters andSetters

    • Eclipse will automatically buildgetters/setters from instance variables – R-click anywhere in code

     – Choose Source Generate Getters and Setters

     – However, if you later click on instance variable and do

    Refactor Rename, Eclipse will not automaticallyrename the accessor methods

    22

  • 8/18/2019 04 Java OOP More

    11/25

    More Details on Getters andSetters

    • 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 evenquite common to have classes containing only immutablefields (immutable classes)

    public class Ship {

    private final String shipName;

    public Ship(…) { shipName = …; … }

    public String getName() { return(shipName); }

    // No setName method23

    More Details on Getters andSetters

    • Getter/setter names need not correspond toinstance variable names – Common to do so if there is a simple correspondence, but

    this is not required • Notice on previous page that instance var was

    “shipName”, but methods were “getName” and “setName”

     –  In fact, there doesn’t even have to be a correspondinginstance variable

    public class Customer {

    public String getFirstName() { getFromDatabase(…); }

    public void setFirstName(…) { storeInDatabase(…); }

    public double getBonus() { return(Math.random()); }

    }24

  • 8/18/2019 04 Java OOP More

    12/25

    © 2015 Marty Hall

    Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Inheritance

    25

    Q: What is the object-oriented way of getting rich?

     A: In heri tance.

    Overview

    • Ideas – You can make a class that “inherits” characteristics of

    another class• The original class is called “parent class”, “super class”, or

    “base class”. The new class is called “child class”,“subclass”, or “extended class”.

     – The child class has access to all non-private methods ofthe parent class.

    • No special syntax need to call inherited methods

    • Syntax example –  public class ChildClass extends ParentClass { … }

    26

  • 8/18/2019 04 Java OOP More

    13/25

    Motivation

    • Supports primary goal of OOP – Supports the key OOP principle of code reuse (i.e., don’t

    write the same code twice) – You can design class hierarchies so that shared behavior

    is inherited by all classes that need it

    27

    Simple Example

    • Person public class Person {

     public String getFirstName() { … }

     public String getLastName() { … }

    }

    • Employee public class Employee extends Person {

     public double getSalary() { … }

     public String getEmployeeInfo() {

    return(getFirstName() + " " + getLastName() +

    " earns " + getSalary());

    }

    }28

  • 8/18/2019 04 Java OOP More

    14/25

    Ship Example: Inheritance

     public 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);

    }

    @Override // Optional -- discussed later

     public void printLocation() {System.out.print(getColor().toUpperCase() + " ");super.printLocation();

    }...

    }29

    Inheritance Example: Testing public class SpeedboatTest {

     public static void main(String[] args) {

    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();

    s3.printLocation();

    }

    }

    30

  • 8/18/2019 04 Java OOP More

    15/25

    Inheritance Example: Result

    • Compiling and running in Eclipse – Save SpeedBoatTest.java

     – R-click, Run As Java Application

    • Compil ing and running manually> javac ship5\SpeedboatTest.java

     –  The above calls javac on Speedboat.java and Ship.javaautomatically

    > java ship5.SpeedboatTest

    • OutputRED Speedboat1 is at (20,0).

    BLUE Speedboat2 is at (-1.41421,1.41421).

    Ship1 is at (-1.41421,1.41421).

    31

    Ship Inheritance Example:Major Points

    • Format for defining subclasses – And nomenclature (parent/child, super/sub,

     base/extended)

    • Using inherited methods

    • Using super(…) for inherited constructors

     – Only when the zero-arg constructor is not OK • The most common case is to omit super and use zero-arg

    constructor of parent, but super is used moderately often

    • Using super.someMethod(…) for inheritedmethods – Only when there is a name conflict

    • Used very rarely

    32

  • 8/18/2019 04 Java OOP More

    16/25

    © 2015 Marty Hall

    Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Review of Packages

    33

    Overview

    • Idea – Organize classes in groups.

    • Syntax – Make folder called somepackage

    • In Eclipse, R-click on “src” and do New Package

     – Put “package somepackage” at top of file•  Automatic in Eclipse

     – To use code from another package• put “import somepackage.*” below your package

    statement

    34

  • 8/18/2019 04 Java OOP More

    17/25

    Motivation

    •  Avoiding name conflicts – Team members can work on different parts of project

    without worrying about what class names other teams use• Different versions for testing

     – For example, in next section, I have three packages:shapes1, shapes1, shapes3. They have variations on waysto make shapes where you can sum their areas.

    • But I use same core class names (Circle, Rectangle, etc.)in each of the packages

    35

    Running Packaged Code thathas “ main”

    • From Eclipse – Same as always: R-click, Run As Application

    • From command line – Go to top-level of package hierarchy, i.e., for simple

     packages, the folder above the one containing the Java

    code – Use the fully-qualified name, i.e., including package

    > java packagename.Classname ...

    36

  • 8/18/2019 04 Java OOP More

    18/25

    © 2015 Marty Hall

    Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    The toString Method

    37

    Overview

    • Idea –  If you give a class a toString method, that method is

    automatically called whenever •  An object of that class is converted to a String

    •  An object of that class is printed

    • Example public class Person {/ / Mai n code cover ed ear l i er

    @Override

     public String toString() {

    return("PERSON: " + getFullName());

    }

    }38

  • 8/18/2019 04 Java OOP More

    19/25

    Preview of @Override

    • Oddit ies of toString – We write the method, but we never call it

     –  If we spell method wrong, we don’t know until run time• @Override useful for both issues; more details later 

    • What will be printed? public class Person {

    ...

     public void tostring() { return(getFullName()); }

    }

    ...Person p = new Person(...);

    System.out.println(p);

    39

    © 2015 Marty Hall

    Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Example: Person Class

    40

  • 8/18/2019 04 Java OOP More

    20/25

    Iterations of Person

    • Last lecture: four i terations of Person –  Instance variables

     – Methods – Constructors

     – Constructors with “this” variable

    • This lecture – Person class

    • Change instance vars to private, add accessor methods

    •  Add JavaDoc comments

    • Use toString

     – Employee class• Make a class based on Person that has all of the

    information of a Person, plus new data41

    Person Class (Part 1)/** A class that represents a person's given name

    * and family name.

    */

     public class Person {

     private String firstName, lastName;

     public Person(String firstName,String lastName) {

    this.firstName = firstName;

    this.lastName = lastName;

    }

    42

  • 8/18/2019 04 Java OOP More

    21/25

    Person Class (Part 2)

    /** The person's given (first) name. */

     public String getFirstName() {

    return (firstName);

    }

     public void setFirstName(String firstName) {

    this.firstName = firstName;

    }

    43

    Person Class (Part 3)/** The person's family name (i.e.,* last name or surname).*/

     public String getLastName() {return (lastName);

    }

     public void setLastName(String lastName) {this.lastName = lastName;

    }

    /** The person's given name and family name, printed * in American style, with given name first and * a space in between.*/

     public String getFullName() {return(firstName + " " + lastName);

    }44

  • 8/18/2019 04 Java OOP More

    22/25

    Employee Class (Part 1)

    /** Represents people that work at a company. */

     public class Employee extends Person {

     private int employeeId; private String companyName;

     public Employee(String firstName, String lastName,int employeeId, String companyName) {

    super(firstName, lastName);this.employeeId = employeeId;this.companyName = companyName;

    }

    45

    Employee Class (Part 2)/** The ID of the employee, with the assumption that* lower numbers are people that started working at* the company earlier than those with higher ids.*/ public int getEmployeeId() {

    return (employeeId);}

     public void setEmployeeId(int employeeId) {this.employeeId = employeeId;

    }

    46

  • 8/18/2019 04 Java OOP More

    23/25

    Employee Class (Part 3)

    /** The name of the company that the person* works for.*/

     public String getCompanyName() {return (companyName);

    }

     public void setCompanyName(String companyName) {this.companyName = companyName;

    }}

    47

    © 2015 Marty Hall

    Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Wrap-Up

    48

  • 8/18/2019 04 Java OOP More

    24/25

    Java OOP References

    • Online –  “OOP Concepts” section in Oracle Java Tutorial. See also “Classes

    and Objects” and “Interfaces and Inheritance”.• http://docs.oracle.com/javase/tutorial/java/

    • Books –  Murach’s Java SE (Murach, Steelman, and Lowe)

    • Excellent Java intro for beginners to Java (but not first-timeprogrammers). Very good OOP section.

     –  Thinking in Java (Bruce Eckel)• Perhaps not quite as good as Murach’s book in general, but

    possibly the best OOP coverage of any Java programming book.

     –  Effective Java, 2nd  Edition (Josh Bloch)

    • In my opinion, by far the best Java best-practices book ever written.Fantastic coverage of OOP best practices.

     –  However, very advanced. Other than the OOP chapter, you won’t understandmuch unless you have been doing Java fulltime for at least a year.

     –  Even experts will learn a lot from this book.49

    Summary

    • Overloading –  You can have multiple methods or constructors with the same

    name. They must differ in argument signatures

    • Best practices –  Make all instance variables private. Hook them to the outside

    with getBlah and/or setBlah

     –  Use JavaDoc-style comments from the very beginning

    • Inheritance –  public class Subclass extends Superclass { … }

    • Non-private methods available with no special syntax

    • Organization –  Put all code in packages

     –  Make output more readable by implementing toString

    50

  • 8/18/2019 04 Java OOP More

    25/25

    © 2015 Marty Hall

    Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Questions?

    51

    More info:http://courses.coreservlets.com/Course-Materials/java.html –General Java programming tutorial

    http://www.coreservlets.com/java-8-tutorial/ –Java 8 tutorial

    http://courses.coreservlets.com/java-training.html – Customized Java training courses, at public venues or onsite at your organizationhttp://coreservlets.com/ –JSF 2, PrimeFaces, Java 7 or 8, Ajax, jQuery, Hadoop, RESTful Web Services, Android, HTML5, Spring, Hibernate, Servlets, JSP, GWT, and other Java EE training

    Many additional free tutorials at coreservlets.com (JSF, Android, Ajax, Hadoop, and lots more)


Recommended