620 likes | 757 Views
More OOP. Lecturer :Royal University Of Phnom Penh Name :Chim Bunthoeurn Email : cbunthoeurn@yahoo.com Tel :012-899-304. Topics. Basic Concepts of OOP Inheritance Abstract class Interface Polymorphism Package. Basic Concepts of OO. An object has
E N D
More OOP Lecturer :Royal University Of Phnom Penh Name :Chim Bunthoeurn Email :cbunthoeurn@yahoo.com Tel :012-899-304
Topics • Basic Concepts of OOP • Inheritance • Abstract class • Interface • Polymorphism • Package Lecturer : chim bunthoeurn
Basic Concepts of OO • An object has • state: defined by the set of fields or attributes. • behavior: defined by the set of methods or operation that can be applied to the object. • identity: determined at the creation time. • Class • A template for creating objects. • Objects of the same class exhibit the same behavior. They may have different states. Lecturer : chim bunthoeurn
Objects and Classes In real world terms: • An object represents an individual entity or thing. • A class represents a group of objects that exhibit some common characteristics or behavior. • Classes are resulted from classification. • Examples of classes in real world: • Students, Graduate students • Undergraduate students • MS students • Ph.D. students Lecturer : chim bunthoeurn
Objects and Classes In programming terms: • A class defines a self-contained software component that represents a real world class. • The design of classes should follows the basic principles of object-orientation: • modularity • encapsulation • Each object is an instance of its class. • A class defines the common characteristics of its instances: • the behaviors and • the templates of the fields. • Each object has its own state, i.e., the values of the fields. Lecturer : chim bunthoeurn
Class Declaration • A class contains data (variable, field) declarations and method declarations • Variables declared at the class level can be used by all methods in that class • Variables declared within a method can only be used in that method • A method declaration specifies the code that will be executed when the method is invoked (or called) Lecturer : chim bunthoeurn
Class Declaration Syntax [ ClassModifiers ] class ClassName [ extends SuperClass ] [ implements Interface1, Interface2 ...] { ClassMemberDeclarations} Lecturer : chim bunthoeurn
Class Visibility • publicAccessible everywhere. One public class allowed per file. The file must be named ClassName.java • default Accessible within the current package. • Other class modifiers: • abstractA class that contains abstract methods • finalNo subclasses Lecturer : chim bunthoeurn
Field and Method Declaration [ MethodModifiers ] ResultType Name ( [ ParameterList ] ) { Statements} [ FieldModifiers ] Type FieldName1 [ = Initializer1 ] , FieldName2 [ = Initializer2 ] ...; Lecturer : chim bunthoeurn
public protected package private The class itself Yes Yes Yes Yes Classes in the same package Yes Yes Yes No Subclasses in a different package Yes Yes No No Non-subclasses in a different package Yes No No No Visibility Lecturer : chim bunthoeurn
Relationship among Classes:Composition • Has-a relation • Example: a student has a • address (type: Address) • faculty advisor (type: Faculty) • etc. Lecturer : chim bunthoeurn
Class Diagram: Composition Lecturer : chim bunthoeurn
Relationship among Classes:Inheritance • A mechanism to organize classes by commonalities. • subclasses, specialization • superclass, generalization • Is-a relation • Example: • A graduate student is a student. • A Master student is a graduate student. • A Ph.D. student is a graduate student. • An undergraduate student is a student. Lecturer : chim bunthoeurn
Class Diagram: Inheritance Lecturer : chim bunthoeurn
Encapsulation • external view: for the users of the classs, client view • internal view: for the developers of the class, implementer view • visibility: • public, • protected, • package (default), • private Lecturer : chim bunthoeurn
Example: Coin.java public class Coin { public final int HEADS = 0; public final int TAILS = 1; private int face; public Coin (){ flip(); } public void flip (){ face = (int) (Math.random() * 2); } Lecturer : chim bunthoeurn
Example: Coin.java public int getFace () { return face; } public String toString() { String faceName; if (face == HEADS) faceName = "Heads"; else faceName = "Tails"; return faceName; } } Lecturer : chim bunthoeurn
Example: CountFlips.java public class CountFlips { public static void main (String[] args) { final int NUM_FLIPS = 1000; int heads = 0, tails = 0; Coin myCoin = new Coin(); for (int count=1; count <= NUM_FLIPS; count++) { myCoin.flip(); if (myCoin.getFace() == myCoin.HEADS) heads++; else tails++; } System.out.println("The number flips: " + NUM_FLIPS); System.out.println("The number of heads: " + heads); System.out.println("The number of tails: " + tails); } } Lecturer : chim bunthoeurn
Example: FlipRace:java public class FlipRace { public static void main (String[] args) { final int GOAL = 3; int count1 = 0, count2 = 0; // Create two separate coin objects Coin coin1 = new Coin(); Coin coin2 = new Coin(); while (count1 < GOAL && count2 < GOAL) { coin1.flip(); coin2.flip(); System.out.print ("Coin 1: " + coin1); System.out.println (" Coin 2: " + coin2); count1 = (coin1.getFace() == coin1.HEADS) ? count1+1 : 0; count2 = (coin2.getFace() == coin2.HEADS) ? count2+1 : 0; } Lecturer : chim bunthoeurn
Example: FlipRace:java // Determine the winner if (count1 < GOAL) { System.out.println("Coin 2 Wins!"); } else if (count2 < GOAL) { System.out.println("Coin 1 Wins!"); } else { System.out.println("It's a TIE!"); } } } Lecturer : chim bunthoeurn
Method Overloading • Two or more methods/constructors with the same name but different numbers or different types of parameters:void methodA(int i)void methodA(int i, int j) void methodB(int i)void methodB(float f) • Avoid overloading Lecturer : chim bunthoeurn
Special Methods • public boolean equals(Object o) • o1.equals(o2)versuso1 == o2 • The equals() method tests the equality of two objects. • The == operator tests the identity of two objects. • When compare two strings, use s1.equals(s2) instead of s1 == s2. • public String toString() • returns a string representation of the state of the object Lecturer : chim bunthoeurn
Example: Account.java import java.text.NumberFormat; public class Account { private NumberFormat fmt = NumberFormat.getCurrencyInstance(); private final double RATE = 0.045; // interest rate of 4.5% private long acctNumber; private double balance; private String name; public Account(String owner, long account, double initial) {name = owner; acctNumber = account; balance = initial; } Lecturer : chim bunthoeurn
Example: Account.java public double deposit (double amount) { if (amount < 0) { // deposit value is negative System.out.println(); System.out.println("Error: ..."); System.out.println(acctNumber + " " + fmt.format(amount)); } else { balance = balance + amount; } return balance; } Lecturer : chim bunthoeurn
Example: Account.java public double withdraw(double amount, double fee) { amount += fee; if (amount < 0) { // withdraw value is negative System.out.println ("Error: ..."); } else if (amount > balance) { // withdraw value exceeds balance System.out.println ("Error: ..."); } else { balance = balance - amount; } return balance; } Lecturer : chim bunthoeurn
Example: Account.java public double addInterest () { balance += (balance * RATE); return balance; } public double getBalance () { return balance; } public long getAccountNumber () { return acctNumber; } public String toString () { return (acctNumber + "\t" + name + "\t" + fmt.format(balance)); } Lecturer : chim bunthoeurn
Example: BankAccount.java public class BankAccounts { public static void main (String[] args) { Account acct1 = new Account("Ted Murphy", 72354, 102.56); Account acct2 = new Account("Jane Smith", 69713, 40.00); Account acct3 = new Account("Edward Demsey", 93757, 759.32); acct1.deposit (25.85); double smithBalance = acct2.deposit (500.00); System.out.println( "Smith balance after deposit: " + smithBalance); System.out.println( "Smith balance after withdrawal: " + acct2.withdraw (430.75, 1.50)); Lecturer : chim bunthoeurn
Example: BankAccount.java acct3.withdraw (800.00, 0.0); // exceeds balance acct1.addInterest(); acct2.addInterest(); acct3.addInterest(); System.out.println(); System.out.println(acct1); System.out.println(acct2); System.out.println(acct3); } } Lecturer : chim bunthoeurn
Inheritance • Inheritance allows a software developer to derive a new class from an existing one, for the purpose of reuse, enhancement, adaptation, etc. • superclass (a.k.a. base class) • subclass (a.k.a. derived class, extended class) • Inheritance models the is-a relationship. • If class E is an extended class of class B, then any object of E can act-as an object of B. Lecturer : chim bunthoeurn
Example: Book.java class Book { protected int pages = 1500; public void pageMessage() { System.out.println("Number of pages: " + pages); } } Lecturer : chim bunthoeurn
Example: Dictionary.java class Dictionary extends Book { private int definitions = 52500; public void definitionMessage() { System.out.println("Number of definitions: " + definitions); System.out.println("Definitions per page: " + definitions/pages); } } Lecturer : chim bunthoeurn
Example: Words.java class Words { public static void main (String[] args) { Dictionary webster = new Dictionary(); webster.pageMessage(); webster.definitionMessage(); } } C:\Examples>java Words Number of pages: 1500 Number of definitions: 52500 Definitions per page: 35 Output: Lecturer : chim bunthoeurn
Extending Classes • Protected visibility • Super constructor • Overriding • Super reference • Single vs. multiple inheritance • A class may have only one superclass Lecturer : chim bunthoeurn
Example: Book2.java class Book2 { protected int pages; public Book2(int pages) { this.pages = pages; } public void pageMessage() { System.out.println("Number of pages: " + pages); } } Lecturer : chim bunthoeurn
Example: Dictionary2.java class Dictionary2 extends Book2 { private int definitions; public Dictionary2(int pages, int definitions) { super (pages); this.definitions = definitions; } public void definitionMessage () { System.out.println("Number of definitions: " + definitions); System.out.println("Definitions per page: " + definitions/pages); } } Lecturer : chim bunthoeurn
Example: Words2.java class Words2 { public static void main (String[] args) { Dictionary2 webster = new Dictionary2(1500, 52500); webster.pageMessage(); webster.definitionMessage(); } } Output: C:\Examples>java Words2 Number of pages: 1500 Number of definitions: 52500 Definitions per page: 35 Lecturer : chim bunthoeurn
Example: Book3.java class Book3 { protected String title; protected int pages; public Book3(String title, int pages) { this.title = title; this.pages = pages; } public void info() { System.out.println("Title: " + title); System.out.println("Number of pages: " + pages); } } Lecturer : chim bunthoeurn
Example: Dictionary3a.java class Dictionary3a extends Book3 { private int definitions; public Dictionary3a(String title, int pages, int definitions) { super (title, pages); this.definitions = definitions; } public void info() { System.out.println("Dictionary: " + title); System.out.println("Number of definitions: " + definitions); System.out.println("Definitions per page: " + definitions/pages); } } Lecturer : chim bunthoeurn
Example: Dictionary3b.java class Dictionary3b extends Book3 { private int definitions; public Dictionary3b(String title, int pages, int definitions) { super (title, pages); this.definitions = definitions; } public void info() { super.info(); System.out.println("Number of definitions: " + definitions); System.out.println("Definitions per page: " + definitions/pages); } } Lecturer : chim bunthoeurn
Example: Books.java class Books { public static void main (String[] args) { Book3 java = new Book3("Introduction to Java", 350); java.info(); System.out.println(); Dictionary3a webster1 = new Dictionary3a("Webster English Dictionary", 1500, 52500); webster1.info(); System.out.println(); Dictionary3b webster2 = new Dictionary3b("Webster English Dictionary", 1500, 52500); webster2.info(); } } Lecturer : chim bunthoeurn
Example: Books.java Output: C:\Examples>java Books Title: Introduction to Java Number of pages: 350 Dictionary: Webster English Dictionary Number of definitions: 52500 Definitions per page: 35 Title: Webster English Dictionary Number of pages: 1500 Number of definitions: 52500 Definitions per page: 35 Lecturer : chim bunthoeurn
Overloading vs. Overriding • Overloading • More than one methods have the same name but different signatures • Overriding • Replacing the implementation of a methods in the superclass with one of your own. • You can only override a method with the same signature. • You can only override instance methods. Lecturer : chim bunthoeurn
The Object Class • The root of Java class hierarchy • Defines some common methods: • public String toString() • public boolean equals(Object other) • If a class does not explicitly declare a superclass, its superclass is Object. Lecturer : chim bunthoeurn
Abstract Class • An abstract class is a class with partial implementation. • It implements behaviors that are common to all subclasses, but defers to the subclasses to implement others (abstract methods). • An abstract class cannot be instantiated • The subclass of an abstract class must override the abstract methods of the parent, or it too will be considered abstract Lecturer : chim bunthoeurn
Interface • Interfaces are classes with no implementation. • Interfaces represent pure design. • Abstract classes represent mixed design and implementation. • An interface consists of only abstract methods and constants, i.e., static and final. • All methods and constants are public. • No static methods. • An interface cannot be instantiated Lecturer : chim bunthoeurn
Inheritance on Interface • Inheritance relation also applies to interfaces • superinterface and subinterface • Multiple inheritance allowed • An interface may extend multiple interfaces • A class my implement multiple interfaces Lecturer : chim bunthoeurn
Type ConversionImplicit Conversion • Numeric variables: Any numeric types can be converted to another numeric type with larger range, e.g. char ==> int, int ==> long, int ==> float, float ==> double. • Object reference: An object reference of class C can be converted to a reference of a superclass of C. Lecturer : chim bunthoeurn
Type ConversionExplicit Conversion (Cast) • Numeric variables: Any numeric types can be explicitly cast to any other numeric type. May lose bits, precision. • Object reference: Cast an object reference of a class to a reference of any other class is: • syntactically allowed; but • runtime checked. Lecturer : chim bunthoeurn
Cast Object References class Student { ... } class Undergraduate extends Student { ... } class Graduate extends Student { ... } Student student1, student2; student1 = new Undergraduate(); // ok student2 = new Graduate(); // ok Graduate student3; student3 = student2; // compilation error student3 = (Graduate) student2; // explicit cast, ok student3 = (Graduate) student1; // compilation ok, run-time error Lecturer : chim bunthoeurn
Polymorphic Reference • A polymorphic reference is one which can refer to different types of objects. Lecturer : chim bunthoeurn