Object-Oriented Java Programming

Slides:



Advertisements
Similar presentations
Object-Oriented Programming. 2 An object, similar to a real-world object, is an entity with certain properties, and with the ability to react in certain.
Advertisements

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Java Programming Strings Chapter 7.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
StringBuffer class  Alternative to String class  Can be used wherever a string is used  More flexible than String  Has three constructors and more.
Fundamental Programming Structures in Java: Strings.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
The java.lang Package chapter 8 Java Certification Study Group February 2, 1998 Seth Ladd.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Topic 4 Inheritance.
Chapter 7: Characters, Strings, and the StringBuilder.
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Strings and Related Classes String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
String and StringBuffer classes
Modern Programming Tools And Techniques-I
Inheritance ITI1121 Nour El Kadri.
Chapter 11 Inheritance and Polymorphism
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
Chapter 11 Inheritance and Polymorphism
String and String Buffers
Object Oriented Programming in Java
IST311 Advanced Issues in OOP: Inheritance and Polymorphism
Interfaces and Inheritance
Continuing Chapter 11 Inheritance and Polymorphism
CS 302 Week 11 Jim Williams, PhD.
Computer Science II Exam 1 Review.
Chapter 9 Inheritance and Polymorphism
Chapter 7: Strings and Characters
MSIS 655 Advanced Business Applications Programming
Polymorphism and access control
Java Inheritance.
Lecture 07 String Jaeki Song.
Polymorphism.
Chapter 14 Abstract Classes and Interfaces
Chapter 8 Class Inheritance and Interfaces
Chapter 11 Inheritance and Polymorphism Part 2
Chapter 10 Thinking in Objects Part 2
Object-Oriented Java Programming
Java String Class String is a class
Presentation transcript:

Object-Oriented Java Programming

Why Java? Simple Platform Independent Safe Multi-Threaded Garbage Collected

Objects, Classes, and Methods Something that occupies memory and has a state Class Pattern (type) of object, or – it’s definition Instance Manifestation in memory of a pattern Method Function or procedure to access object state

Overriding vs Overloading Overload – many functions with the same name but different signature Override – many functions with the same signature, choice is made relative to inheritance

Constructors Overloading public class Point { … } public class Rectangle { private int width = 0; private int height = 0; private Point origin; public Rectangle() { origin = new Point(0, 0); } public Rectangle(Point p, int w, int h) { origin = p; width = w; height = h; } …

Visibility / Access Control Public: Private: Protected: Package:

Example of Access Control Base.java package p1; public class Base { private int u; protected int v; public int w; private void g ( ) { System.out.println(v); } protected void f ( ) { System.out.println(u); g(); } Derived.java package p2; import p1.Base; public class Derived extends Base { void h () { f(); } void k () { g(); } Test.java package p2; import p1.Base; public class Test { public static void main(String[] args) { Base b = new Base(); b.u = 1; // Compilation error b. v = 2; b.w = 3; // OK b.g(); b.f(); Derived d = new Derived(); d.h(); d.k(); }

ThreeDimensionalShape Inheritance Object Shape TwoDimensionalShape ThreeDimensionalShape Circle Square Triangle Sphere Cube public class B extends A { … } public class A { … }

Why Inheritance Code reuse Flexibility Multiple implementations Keep related data close to the relevant operations “IS-A” vs “HAS-A”

Class Object class Object { … public boolean equals ( Object obj ) { … } public String toString() { …} }

Method equals ( ) ==: identical references to objects String s = “Hello”; String t = new String(“Hello”); if ( s == t ) System.out.println( “the same”); // condition is false and print nothing! if ( s.equals(t) ) System.out.println( “the same”); equals: equality of objects Already implemented in class Object Need to define for your class : Point p1 = new Point (10, 10); Point p2 = new Point (5, 5); Rectangle rec1 = new Rectangle (p1, 5,10); Rectangle rec2 = new Rectnagle (p2, 5, 10); if ( rec1 == rec2 ) System.out.println(“the same”); if ( rec1.equals(rec2) ) System.out.println(“the same”);

Overide equals ( ) public class Rectangle { … public boolean equals ( Object obj ) Rectangle rec = (Rectangle) obj; return (w == rec.width()) && (h == rec.height()); } Rectangle rec1 = new Rectangle (p1, 5, 10); Rectangle rec2 = new Rectangle (p2, 5, 10); if ( rec1.equals(rec2) ) System.out.println(“the same!”); // condition is true and print “the same”!

Method toString( ) Rectangle rec = new Rectangle (p1, 5, 10); System.out.println( rec ); // prints something like Rectangle@73d6at (class name +@+ hash code of object)

Overide toString( ) public class Rectangle { … { … public String toString() { return “width = ” + w + “, height = ” + h; } Rectangle rec = new Rectangle (p1, 5, 10); System.out.println( rec ); Output: width = 5, height = 10 (instead of Rectangle@73d6at)

Inheritance public class Circle { private Point center; private double radius; public Circle( Point c, double r) { center = c; radius = r; } public double area() { return Math.PI * radius* radius; } public class Rectangle { private Point center; private double width; private double height; public Rectangle( Point c, double w, double h) { center = c; width = w; height = h; } public double area() { return width * height; }

Inheritance (Cont’d) public abstract class Shape { private Point center; public Shape( Point c) { center = c; } public abstract double area(); }

Inheritance (Cont’d) public class Circle extends Shape { public Circle( Point c, double r) super(c); radius = r; } public double area() return Math.PI * radius* radius; public class Rectangle extends Shape { private double width; private double height; public Rectangle( Point c, double w, double h) { super(c); width = w; height = h; } public double area() { return width * height; }

Polymorphism Class Ancestors Multiple Interfaces Abstract classes

Casting Upcasting: Assign a subclass reference to a superclass variable Downcasting: Assign superclass reference to subclass variable

Example of Casting public class Queue { // constructors and instance variables omitted public void enqueue( int x) { … } public int dequeue() { … } public int front() { … } public boolean empty() { … } } public class Deque extends Queue { … public void addFront( int x ) { … } public void deleteRear() { … } Queue q1, q2; Deque d; d = new Deque(); q1 = d; q1.deleteRear(); // Compilation error d = q1; d= (Deque) q1; d.deleteRear(); q2 = new Queue(); d = (Deque) q2; // Runtime error

Dynamic Binding Dynamic Binding A mechanism by which, when the compiler can't determine which method implementation to use in advance, the runtime system (JVM) selects the appropriate method at runtime, based on the class of the object. The process of binding a call to a particular method. This is performed dynamically at run-time.

Dynamic Binding Example class A { void p() { System.out.println(“A.p”); } void q() { System.out.println(“A.q”); } void f() { p(); q(); } } class B extends A { void p() { System.out.println(“B.p”); } void q() { System.out.println(“B.q”); super.q(); } public class Test { public static void main(String[] args) { A a = new A(); a.f(); a = new B(); a.f(); } Print: A.p A.q B.p B.q

Dynamic Binding Example (Cont’d) class A { public void q(){ System.out.println("A.q()"); } class B extends A { public void f(){ System.out.println("B.f()"); super.q(); class C extends B { public void q() { System.out.println("C.q()"); public class D extends C { public static void main(String[] args){ D d = new D(); d.f(); Print: B.f() A.q()

Abstract Class Abstract classes Cannot be instantiated Incomplete: subclasses fill in "missing pieces” To make a class abstract public abstract class Shape {…} Contain one or more abstract methods No implementation E.g., public abstract void draw(); Subclasses: fill in "missing pieces” (i.e., overriding the abstract methods) E.g., Circle, Triangle, Rectangle extends Shape Each must implement draw it is concrete

Example of Abstract Class public class Base { public String m1( ) { return “Base.m1”; } } public abstract class Derived extends Base public abstract String m2( ); public class Derived2 extends Derived public String m2( ) { return "Derived2.m2”;}

Interface No method implementations Java doesn’t allow multiple inheritance: E.g., … C extends A, B … Instead, use Interface E.g., … C implements I1, I2 … One class may implement multiple interfaces Must implement all functions in those interfaces if class is concrete

Interface Example public class Base { public String m1( ) { return “Base.m1”;} } interface Interface1 { String m2( ); } interface Interface2 { String m3(); } public class Derived extends Base implements Interface1, Interface2 public String m2( ) { return "Derived.m2";} public String m3( ) { return "Derived.m3";}

Interface Example (Cont’d) interface Interface1 { String m( String s ); } interface Interface2 { String m( int i ); } public class Derived implements Interface1, Interface2 { public String m(String s) { return “Derived.Interface1.m"; } public String m(int i) { return “Derived.Interface2.m";

Interface Example (Cont’d) interface Interface1 { String m( String s ); } interface Interface2 { String m( String s ); } public class Derived implements Interface1, Interface2 { public String m(String s) { return “Derived.Interface1&Interface2.m"; }

Interface Example (Cont’d) interface Interface1 { String m( String s ); } interface Interface2 { void m( String s ); } public class Derived implements Interface1, Interface2 { public String m(String s) { return “Derived.Interface1.m"; } public void m(int i) { System.out.println( “Derived.Interface2.m“); Derived d = new Derived(); d.m(10); // Compilation error

Interface (Java) vs. Multiple Inheritance (C++) abstract class A { abstract public void f() } class B extends A { public void f(){ System.out.println("B.f()"); class C extends A { public void f() { System.out.println("C.f()"); public class D extends B, C { public static void main(String[] args){ D d = new D(); d.f(); In C++: D* d = new D; d->f(); // Compilation error d->B::f(); // Legal

Interfaces vs. Abstract Classes A class may implement several interfaces An interface cannot provide any code at all Static final constants only A class may extend only one abstract class An abstract class can provide partial code Both instance and static constants are possible

Combination of Abstract Class and Interface public class Base { public String m1( ) { return “Base.m1”; } } interface Interface1 { String m1( ); String m2( ); public abstract class Derived extends Base implements Interface1 { public String m2( ) { return "Derived.m2"; } public class Derived2 extends Derived { public String m1( ) { return "Derived2.m1”; } Derived2 derived2 = new Derived2(); Base base = derived2; tmp = derived2.m1( "Hello" ); // tmp is "Derived2.m1" tmp = base.m1( "Hello" ); tmp = derived2.m2(); // tmp is "Derived.m2"

String Processing Class java.lang.String Class java.lang.StringBuffer Class java.util.StringTokenizer URL: http://java.sun.com/j2se/1.4.2/docs/api/

Important Methods in Class String Method length Determine String length Like arrays, Strings always “know” their size Unlike array, Strings do not have length instance variable Method charAt Get character at specific location in String Method getChars Get entire set of characters in String Method startWith Tests if this string starts with the specified prefix Method split Splits this string around matches of the given regular expression

Important Methods in Class String Comparing String objects Method equals Method equalsIgnoreCase Method compareTo Search for characters in String Method indexOf Method lastIndexOf Create Strings from other Strings Method substring Concatenate two String objects Method concat Method concat String provides static class methods Method valueOf Returns String representation of object, data, etc.

Class StringBuffer Class StringBuffer When String object is created, its contents cannot change Used for creating and manipulating dynamic string data i.e., modifiable Strings Can store characters based on capacity Capacity expands dynamically to handle additional characters Uses operators + and += for String concatenation

Important Methods in StringBuffer Method charAt Return StringBuffer character at specified index Method setCharAt Set StringBuffer character at specified index Method getChars Return character array from StringBuffer Method append Allow data values to be added to StringBuffer Method reverse Reverse StringBuffer contents Method insert Allow data-type values to be inserted into StringBuffer Methods delete and deleteCharAt Allow characters to be removed from StringBuffer

Important Methods in Class StringBuffer Method length Return StringBuffer length Method capacity Return StringBuffer capacity Method setLength Increase or decrease StringBuffer length Method ensureCapacity Set StringBuffer capacity Guarantee that StringBuffer has minimum capacity

Class StringTokenizer Partition String into individual substrings Use delimiter Java offers java.util.StringTokenizer

Important Methods in Class StringTokenizer Constructor StringTokenizer(String str) Constructs a string tokenizer for the specified string Constructor StringTokenizer(String str, String delim) Method hasMoreTokens() Tests if there are more tokens available from this tokenizer's string Method nextToken() Returns the next token from this string tokenizer