Object-oriented
Programming
At the end of this chapter, the learner will be able to:
1) Define classes and objects.
2) Use abstraction and encapsulation to simplify
complicated problems.
3) Utilize inheritance and polymorphism in Java.
4) Define and use abstract classes.
5) Define and implement interfaces.
A L ABELEE IT LearningSeries Your First Java Book ©2009
What is Java?
• It is an object-oriented programming language.
Class:
(blueprint)
Book
Properties
Object:
(instance)
Textbook
Properties
title
author
yearPublished
Your First Java Book
Lesley Abe
2009
Methods Methods
borrow
return
borrow
return
A L ABELEE IT LearningSeries Your First Java Book ©2009
Object Oriented Programming
• Abstraction
– Modeling classes (UML class diagrams)
• Encapsulation
– One object: data and behavior combined
– Information Hiding
• Access levels: private, protected, public, default
– Accessors (get) and Mutators (set)
– interface
• Inheritance
– Superclass and subclass
• Polymorphism
– Overloading
– overriding
A L ABELEE IT LearningSeries Your First Java Book ©2009
Abstraction and Encapsulation
Trainer
-name:String
-height:double
-weight:double
-birthday:Date
+talk(String)
+getName():String
+setName(String)
<<constructor>>
+Trainer()
+Trainer(String,
double, double,
Date)
Name of Class
Attributes/properties
Methods
Trainee
-name:String
-height:double
-weight:double
-birthday:Date
-traineeNumber:int
+talk(String)
+getName():String
+setName(String)
<<constructor>>
+Trainee()
+Trainee(int,String,
double, double,
Date)
Examples:
Accessor (Method)
Mutator (Method)
Default Constructor
Overloaded Constructor
A L ABELEE IT LearningSeries Your First Java Book ©2009
Java Class Implementation
import java.util.Date;
public class Trainer{
private String name;
private double height; //height in cm
private double weight; //weight in kg
private Date birthday;
public Trainer(){ } //Java provides a default constructor when it is not created by the programmer
public Trainer(String name, double height, double weight, Date birthday) {
this.name = name;
this.height = height;
this.weight = weight;
this.birthday = birthday;
}
public void talk(String phrase){
System.out.println(phrase);
}
public String getName() {return name;}
public void setName(String name) {this.name=name;}
}
• Members
– Attributes/fields (Variables) and
methods
• Scope
– Variable and method visibility,
and accessibility
A L ABELEE IT LearningSeries Your First Java Book ©2009
Constructors
public Trainer(){ }
//Java provides a default constructor when it is not created by the programmer
// Always provide a default constructor,s specially when overloading a constructor.
public Trainer (String name, Date birthday) {
this.name = name;
this.height = 180.5;
this.weight = 45.5;
this.birthday = birthday;
}
public Trainer (String name, double height, double weight, Date
birthday) {
this(name, birthday);
this.height = height;
this.weight = weight;
}
//Constructors have no return type. They are called in creating objects, using new.
Modifiers
method name
parameter list in parenthesis
method body, enclosed between
braces
Use this to make a call to another
constructor and it must be in the
constructor’s first line.
A L ABELEE IT LearningSeries Your First Java Book ©2009
Mutator and Accessor
//Accessors have no parameter list. Prefix with get.
public String getName ( ) {return name;}
//Mutators are setters thus they return nothing or void. Prefix with set.
public void setName (String name) {this.name=name;}
modifiers
return type
method name
parameter list in parenthesis
method body, enclosed between
braces
A L ABELEE IT LearningSeries Your First Java Book ©2009
Method Declaration
//method names are verbs
//or verb phrases
public void talk (String phrase){
//declare local variables (only visible
// within the method)
// before they are used
System.out.println(phrase);
}
public static void main (String[] args) throws IOException{
//no need to declare parameters
System.out.print(args[0]);
}
modifiers
return type
method name
parameter (formal) list in
parenthesis
exception list
method body, enclosed between
braces
A L ABELEE IT LearningSeries Your First Java Book ©2009
Access Level
Access
Modifier
Within the
Same
Class
Within the
Same
Package
Within a
Subclass
public Accessible Accessible Accessible
protected Accessible Accessible Accessible
default Accessible Accessible
private Accessible
A L ABELEE IT LearningSeries Your First Java Book ©2009
Coding Conventions
• Camel Case (first letter of the first word is in lowercase,
every first letter of the succeeding words are capitalized,
e.g. isUpdated)
– Class member variables (use Hungarian notation)
– Method parameters
– Methods (Mutators, Accessors)
• Pascal Case (every first letter of the every word is
capitalized, e.g. MyAccount)
– Classes
– Constructors
• ALL CAPS
– Constants (each word separated by underscore)
A L ABELEE IT LearningSeries Your First Java Book ©2009
Scope
• The scope of a variable is defined by where a variable is declared.
In Java, the closest declaration is considered first.
• The this keyword
– To refer to methods of the current class
this.methodName(<parameter/s>)
– To refer to variables of the current class
this.variableName
– To refer to the constructor of the current class
this(<parameter/s>);
for(int ctr=0;ctr<=10;ctr++) System.out.println(ctr);
if(ctr==10) System.out.println(ctr);//error
A L ABELEE IT LearningSeries Your First Java Book ©2009
Variable and Method Invocation
• To declare a new instance of a class, use the syntax:
ClassName objectName = new Constructor(<parameter/s>);
• Invoking/calling Methods
<objectName>.<methodName>(<parameter/s>);
• Invoking Variables
<objectName>.<variableName>;
import java.util.Date;
public class MainClass {
public static void main(String[] args){
Trainer myTrainer = new Trainer(“Splinter”, 150, 50, new Date());
myTrainer.talk(“My name is “+myTrainer.getName());
myTrainer.talk(“I will be your trainer.”);
}
}
parameter (actual) list in
parenthesis
A L ABELEE IT LearningSeries Your First Java Book ©2009
Instance and Class Members
• class member
– all instances of a class share a variable/method
– defined with the keyword static.
– Invoking Methods
<ClassName>.<methodName>(<parameter/s>)
– Invoking Variables
<ClassName>.<variableName>
• instance member
– every object instantiated from that class contains its own copy of
the variable/method
A L ABELEE IT LearningSeries Your First Java Book ©2009
Inheritance
Trainer
<<constructor>>
Trainer(String, double,
double, Date)
Trainee
traineeNumber:int
+getTraineeNumber():int
<<constructor>>
Trainee(String, double,
double, Date)
Human
#name:String
#height:double
#weight:double
#birthday:Date
+talk(String)
+getName():String
+setName(String)
<<constructor>>
Human(String,double
,double,int)
A L ABELEE IT LearningSeries Your First Java Book ©2009
Inheritance
public class Human{
private String name; //What if we made this private? (Originally protected)
protected double height; //height in cm
protected double weight; //weight in kg
protected Date birthday;
public Human(String name, double height, double weight, Date birthday){
this.name = name;
this.height = height;
this.weight = weight;
this.birthday = birthday;
}
public void talk(String phrase){
System.out.println(phrase);
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
// other methods may be implemented
}
public class Trainee extends Human{
static int traineeNumber=0; //class member
public Trainee(){ traineeNumber++; }
public Trainee(String name, double height, double
weight, Date birthday){
super(name, height, weight, birthday);
traineeNumber++;
}
public static int getTraineeNumber(){
return traineeNumber;
}
}
A L ABELEE IT LearningSeries Your First Java Book ©2009
Inheritance
• The super keyword
– To refer to methods of the parent class
super.methodName(<parameter/s>)
– To refer to variables of the parent class
super.variableName
– To refer to the constructor of the parent class
super(<parameter/s>);
Note: super MUST be the first line in the method.
• Single Inheritance
– a class can inherit from only one superclass
A L ABELEE IT LearningSeries Your First Java Book ©2009
Polymorphism
public double computeIdealBodyWeight(){
return 50 + 2.3 *( height/2.4 - 60 );
}
}
package Chapter8.inheritance;
public class Human{
protected String name;
protected double height; //height in cm
protected double weight; //weight
protected Date birthday;
public Human(String name, double height,
double weight, Date birthday)
{
this.name = name;
this.height = height;
this.weight = weight;
this.birthday = birthday;
}
public void talk(String phrase){
System.out.println(phrase);
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
package Chapter8.inheritance;
public class Woman extends Human
{
public Woman(String name, double height, double
weight, int birthday){
super(name, height, weight, birthday);
}
public double computeIdealBodyWeight(){
return 45.5 + 2.3 *(getHeight()/2.4 - 60 );
}
}
Method
Overriding
Although they may have the
same method signature,
Overriding method cannot be
less accessible than the method
it is overriding.
A L ABELEE IT LearningSeries Your First Java Book ©2009
Polymorphism
public class Athlete2 extends Human {
boolean isMale = true;
public Athlete2(String name, double height, double weight, Date birthday){
super(name, height, weight, birthday);
}
public Athlete2(String name, double height, double weight, Date birthday, boolean isMale){
this(name, height, weight, birthday);
this.isMale = isMale;
}
public double ComputeIdealBodyWeight(){
if (isMale){
return super.ComputeIdealBodyWeight();
}
else{
return 45.5 + 2.3 *(getHeight()/2.4 - 60 );
}
}
}
Method
Overloading
Overloaded methods have the
same method name but different
parameter/s (type, order). Each
method must be unique in a
class.
A L ABELEE IT LearningSeries Your First Java Book ©2009
Abstract class
Trainer
<<constructor>>
Trainer(String,
double, double,
Date)
computeIdealBodyWeight():
double
Trainee
traineeNumber:int
+getTraineeNumber():int
<<constructor>>
Trainee(String, double,
double, Date)
computeIdealBodyWeight():double
{abstract}
Human
-name:String
-height:double
-weight:double
-birthday:Date
+talk(String)
+getName():String
+setName(String)
+{abstract}
computeIdealBodyWeight(
):double
<<constructor>>
Human(String,double,dou
ble,int)
A L ABELEE IT LearningSeries Your First Java Book ©2009
Abstract Classpackage Chapter8.inheritance;
public abstract class AbstractHuman{
protected String name;
protected double height; //height in cm
protected double weight; //weight in kg
protected Date birthday;
public AbstractHuman(String name, double height, double weight, Date birthday){
this.name = name; this.height = height; this.weight = weight; this. birthday = birthday;
}
public void talk(String phrase){
System.out.println(phrase);
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setHeight(double height){
this.height = height;
}
public double getHeight(){
return this.height;
}
public abstract double computeIdealBodyWeight();
}
Subclasses must override this method
Abstract classes cannot be instantiated.
A L ABELEE IT LearningSeries Your First Java Book ©2009
Interface
public interface <interface_Name>{
  //constant variable declarations
  //method signatures
}
• Interfaces are used to simulate multiple inheritance.
Note:
A solid arrow is used to depict inheritance when a class extends another.
For example, EmployeeTrainer extends the Human class. A dashed arrow is
used to imply that a class implements an interface. For example,
EmployeeTrainer implements the Employee interface.
A L ABELEE IT LearningSeries Your First Java Book ©2009
Interface
EmployeeTrainer
-salary:double
<<constructor>>
EmployeeTrainer
(String, double,
double, Date)
<<interface>>
Employee
+getSalary():double
+setSalary(double)
Human
-name:String
-height:double
-weight:double
-birthday:Date
+talk(String)
+getName():String
+setName(String)
<<constructor>>
Human(String,double
,double, Date
A L ABELEE IT LearningSeries Your First Java Book ©2009
Interface
public interface Employee {
public double getSalary();
public void setSalary(double);
}
public class EmployeeTrainer extends Human implements Employee{
private double salary;
public EmployeeTrainer(String name, double height, double weight, Date bday){
super(name, height, weight, bday);
}
public double getSalary() { return salary; }
public void setSalary(double) {this.salary= salary; }
}
A L ABELEE IT LearningSeries Your First Java Book ©2009
Review
• Define the following:
– Abstraction
– Encapsulation
– Inheritance
– Interface
– Abstract class
– Polymorphism
– Superclass
– subclass
• Give an example of a
UML class diagram.
• What is the difference
between class members
and instance members?
• What is the difference
between overloading
and overriding?
• Differentiate the
following: public,
private, protected

Lecture Notes

  • 1.
    Object-oriented Programming At the endof this chapter, the learner will be able to: 1) Define classes and objects. 2) Use abstraction and encapsulation to simplify complicated problems. 3) Utilize inheritance and polymorphism in Java. 4) Define and use abstract classes. 5) Define and implement interfaces.
  • 2.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 What is Java? • It is an object-oriented programming language. Class: (blueprint) Book Properties Object: (instance) Textbook Properties title author yearPublished Your First Java Book Lesley Abe 2009 Methods Methods borrow return borrow return
  • 3.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Object Oriented Programming • Abstraction – Modeling classes (UML class diagrams) • Encapsulation – One object: data and behavior combined – Information Hiding • Access levels: private, protected, public, default – Accessors (get) and Mutators (set) – interface • Inheritance – Superclass and subclass • Polymorphism – Overloading – overriding
  • 4.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Abstraction and Encapsulation Trainer -name:String -height:double -weight:double -birthday:Date +talk(String) +getName():String +setName(String) <<constructor>> +Trainer() +Trainer(String, double, double, Date) Name of Class Attributes/properties Methods Trainee -name:String -height:double -weight:double -birthday:Date -traineeNumber:int +talk(String) +getName():String +setName(String) <<constructor>> +Trainee() +Trainee(int,String, double, double, Date) Examples: Accessor (Method) Mutator (Method) Default Constructor Overloaded Constructor
  • 5.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Java Class Implementation import java.util.Date; public class Trainer{ private String name; private double height; //height in cm private double weight; //weight in kg private Date birthday; public Trainer(){ } //Java provides a default constructor when it is not created by the programmer public Trainer(String name, double height, double weight, Date birthday) { this.name = name; this.height = height; this.weight = weight; this.birthday = birthday; } public void talk(String phrase){ System.out.println(phrase); } public String getName() {return name;} public void setName(String name) {this.name=name;} } • Members – Attributes/fields (Variables) and methods • Scope – Variable and method visibility, and accessibility
  • 6.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Constructors public Trainer(){ } //Java provides a default constructor when it is not created by the programmer // Always provide a default constructor,s specially when overloading a constructor. public Trainer (String name, Date birthday) { this.name = name; this.height = 180.5; this.weight = 45.5; this.birthday = birthday; } public Trainer (String name, double height, double weight, Date birthday) { this(name, birthday); this.height = height; this.weight = weight; } //Constructors have no return type. They are called in creating objects, using new. Modifiers method name parameter list in parenthesis method body, enclosed between braces Use this to make a call to another constructor and it must be in the constructor’s first line.
  • 7.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Mutator and Accessor //Accessors have no parameter list. Prefix with get. public String getName ( ) {return name;} //Mutators are setters thus they return nothing or void. Prefix with set. public void setName (String name) {this.name=name;} modifiers return type method name parameter list in parenthesis method body, enclosed between braces
  • 8.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Method Declaration //method names are verbs //or verb phrases public void talk (String phrase){ //declare local variables (only visible // within the method) // before they are used System.out.println(phrase); } public static void main (String[] args) throws IOException{ //no need to declare parameters System.out.print(args[0]); } modifiers return type method name parameter (formal) list in parenthesis exception list method body, enclosed between braces
  • 9.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Access Level Access Modifier Within the Same Class Within the Same Package Within a Subclass public Accessible Accessible Accessible protected Accessible Accessible Accessible default Accessible Accessible private Accessible
  • 10.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Coding Conventions • Camel Case (first letter of the first word is in lowercase, every first letter of the succeeding words are capitalized, e.g. isUpdated) – Class member variables (use Hungarian notation) – Method parameters – Methods (Mutators, Accessors) • Pascal Case (every first letter of the every word is capitalized, e.g. MyAccount) – Classes – Constructors • ALL CAPS – Constants (each word separated by underscore)
  • 11.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Scope • The scope of a variable is defined by where a variable is declared. In Java, the closest declaration is considered first. • The this keyword – To refer to methods of the current class this.methodName(<parameter/s>) – To refer to variables of the current class this.variableName – To refer to the constructor of the current class this(<parameter/s>); for(int ctr=0;ctr<=10;ctr++) System.out.println(ctr); if(ctr==10) System.out.println(ctr);//error
  • 12.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Variable and Method Invocation • To declare a new instance of a class, use the syntax: ClassName objectName = new Constructor(<parameter/s>); • Invoking/calling Methods <objectName>.<methodName>(<parameter/s>); • Invoking Variables <objectName>.<variableName>; import java.util.Date; public class MainClass { public static void main(String[] args){ Trainer myTrainer = new Trainer(“Splinter”, 150, 50, new Date()); myTrainer.talk(“My name is “+myTrainer.getName()); myTrainer.talk(“I will be your trainer.”); } } parameter (actual) list in parenthesis
  • 13.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Instance and Class Members • class member – all instances of a class share a variable/method – defined with the keyword static. – Invoking Methods <ClassName>.<methodName>(<parameter/s>) – Invoking Variables <ClassName>.<variableName> • instance member – every object instantiated from that class contains its own copy of the variable/method
  • 14.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Inheritance Trainer <<constructor>> Trainer(String, double, double, Date) Trainee traineeNumber:int +getTraineeNumber():int <<constructor>> Trainee(String, double, double, Date) Human #name:String #height:double #weight:double #birthday:Date +talk(String) +getName():String +setName(String) <<constructor>> Human(String,double ,double,int)
  • 15.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Inheritance public class Human{ private String name; //What if we made this private? (Originally protected) protected double height; //height in cm protected double weight; //weight in kg protected Date birthday; public Human(String name, double height, double weight, Date birthday){ this.name = name; this.height = height; this.weight = weight; this.birthday = birthday; } public void talk(String phrase){ System.out.println(phrase); } public void setName(String name){ this.name = name; } public String getName(){ return this.name; } // other methods may be implemented } public class Trainee extends Human{ static int traineeNumber=0; //class member public Trainee(){ traineeNumber++; } public Trainee(String name, double height, double weight, Date birthday){ super(name, height, weight, birthday); traineeNumber++; } public static int getTraineeNumber(){ return traineeNumber; } }
  • 16.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Inheritance • The super keyword – To refer to methods of the parent class super.methodName(<parameter/s>) – To refer to variables of the parent class super.variableName – To refer to the constructor of the parent class super(<parameter/s>); Note: super MUST be the first line in the method. • Single Inheritance – a class can inherit from only one superclass
  • 17.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Polymorphism public double computeIdealBodyWeight(){ return 50 + 2.3 *( height/2.4 - 60 ); } } package Chapter8.inheritance; public class Human{ protected String name; protected double height; //height in cm protected double weight; //weight protected Date birthday; public Human(String name, double height, double weight, Date birthday) { this.name = name; this.height = height; this.weight = weight; this.birthday = birthday; } public void talk(String phrase){ System.out.println(phrase); } public void setName(String name){ this.name = name; } public String getName(){ return this.name; } package Chapter8.inheritance; public class Woman extends Human { public Woman(String name, double height, double weight, int birthday){ super(name, height, weight, birthday); } public double computeIdealBodyWeight(){ return 45.5 + 2.3 *(getHeight()/2.4 - 60 ); } } Method Overriding Although they may have the same method signature, Overriding method cannot be less accessible than the method it is overriding.
  • 18.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Polymorphism public class Athlete2 extends Human { boolean isMale = true; public Athlete2(String name, double height, double weight, Date birthday){ super(name, height, weight, birthday); } public Athlete2(String name, double height, double weight, Date birthday, boolean isMale){ this(name, height, weight, birthday); this.isMale = isMale; } public double ComputeIdealBodyWeight(){ if (isMale){ return super.ComputeIdealBodyWeight(); } else{ return 45.5 + 2.3 *(getHeight()/2.4 - 60 ); } } } Method Overloading Overloaded methods have the same method name but different parameter/s (type, order). Each method must be unique in a class.
  • 19.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Abstract class Trainer <<constructor>> Trainer(String, double, double, Date) computeIdealBodyWeight(): double Trainee traineeNumber:int +getTraineeNumber():int <<constructor>> Trainee(String, double, double, Date) computeIdealBodyWeight():double {abstract} Human -name:String -height:double -weight:double -birthday:Date +talk(String) +getName():String +setName(String) +{abstract} computeIdealBodyWeight( ):double <<constructor>> Human(String,double,dou ble,int)
  • 20.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Abstract Classpackage Chapter8.inheritance; public abstract class AbstractHuman{ protected String name; protected double height; //height in cm protected double weight; //weight in kg protected Date birthday; public AbstractHuman(String name, double height, double weight, Date birthday){ this.name = name; this.height = height; this.weight = weight; this. birthday = birthday; } public void talk(String phrase){ System.out.println(phrase); } public void setName(String name){ this.name = name; } public String getName(){ return this.name; } public void setHeight(double height){ this.height = height; } public double getHeight(){ return this.height; } public abstract double computeIdealBodyWeight(); } Subclasses must override this method Abstract classes cannot be instantiated.
  • 21.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Interface public interface <interface_Name>{   //constant variable declarations   //method signatures } • Interfaces are used to simulate multiple inheritance. Note: A solid arrow is used to depict inheritance when a class extends another. For example, EmployeeTrainer extends the Human class. A dashed arrow is used to imply that a class implements an interface. For example, EmployeeTrainer implements the Employee interface.
  • 22.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Interface EmployeeTrainer -salary:double <<constructor>> EmployeeTrainer (String, double, double, Date) <<interface>> Employee +getSalary():double +setSalary(double) Human -name:String -height:double -weight:double -birthday:Date +talk(String) +getName():String +setName(String) <<constructor>> Human(String,double ,double, Date
  • 23.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Interface public interface Employee { public double getSalary(); public void setSalary(double); } public class EmployeeTrainer extends Human implements Employee{ private double salary; public EmployeeTrainer(String name, double height, double weight, Date bday){ super(name, height, weight, bday); } public double getSalary() { return salary; } public void setSalary(double) {this.salary= salary; } }
  • 24.
    A L ABELEEIT LearningSeries Your First Java Book ©2009 Review • Define the following: – Abstraction – Encapsulation – Inheritance – Interface – Abstract class – Polymorphism – Superclass – subclass • Give an example of a UML class diagram. • What is the difference between class members and instance members? • What is the difference between overloading and overriding? • Differentiate the following: public, private, protected