CS18000: Problem Solving and Object-Oriented Programming

Slides:



Advertisements
Similar presentations
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Advertisements

CS18000: Problem Solving and Object-Oriented Programming.
Data Structures Lecture 2 Fang Yu Department of Management Information Systems National Chengchi University Fall 2011.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Abstract Classes.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Interfaces.
Object Oriented Software Development
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
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.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
The Java Programming Language
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Methods Methods are how we implement actions – actions that objects can do, or actions that can be done to objects. In Alice, we have methods such as move,
Classes, Interfaces and Packages
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
A High Flying Overview CS139 – Fall 2006 How far we have come.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Java 5 Class Anatomy. User Defined Classes To this point we’ve been using classes that have been defined in the Java standard class library. Creating.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Lecture 5:Interfaces and Abstract Classes
Topic: Classes and Objects
EECE 310: Software Engineering
Concepts of Object Oriented Programming
Chapter 7 User-Defined Methods.
3 Introduction to Classes and Objects.
CS 215 Final Review Ismail abumuhfouz Fall 2014.
2.7 Inheritance Types of inheritance
Java Primer 1: Types, Classes and Operators
Methods Chapter 6.
Chapter 3: Using Methods, Classes, and Objects
About the Presentations
Prof: Dr. Shu-Ching Chen TA: Samira Pouyanfar Hector Cen Fall 2017
Chapter 4: Writing Classes
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
OOP’S Concepts in C#.Net
CS139 – Fall 2010 How far we have come
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Object Based Programming
Class Inheritance (Cont.)
Defining Classes and Methods
Interface.
Java Programming Language
Lecture 22 Inheritance Richard Gesick.
Group Status Project Status.
Interfaces.
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
CS18000: Problem Solving and Object-Oriented Programming
Inheritance Inheritance is a fundamental Object Oriented concept
Barb Ericson Georgia Institute of Technology Oct 2005
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Abstract Classes and Interfaces
Java Programming Language
More on Creating Classes
Review of Previous Lesson
Interfaces,Packages and Threads
CS18000: Problem Solving and Object-Oriented Programming
INTERFACES Explained By: Sarbjit Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
Introduction to Methods and Interfaces
Introduction to Classes and Objects
Presentation transcript:

CS18000: Problem Solving and Object-Oriented Programming Welcome slide for display pre-bell.

Interfaces Encapsulation

Interface Concepts Interface: Examples: A point where two systems interact Typically asymmetric: one system “defines” the interface, the other system “uses” it Examples: Graphical User Interface (GUI): user -> computer Application Programming Interface (API): application program -> library of related methods

Java Class A Java class provides one form of interface Public members (methods, mainly) define the interface to “clients” (users) of that class Class interface consists of Public method signatures (what the method expects) Method return types (what the method returns) The Java language abstracts this idea one step further…

Java Interface Defines a “contract” between A class that defines the interface, and A class that implements (uses) the interface Any class that implements the interface must provide implementations for all the method bodies given in the interface definition (except default methods)

Interface Syntax A class-like declaration But… interface Doable { … } Exists in own file Includes method declarations But… No method bodies (except default methods) No fields (other than constants) An interface is like a class in which you forgot to declare the fields and left out the method bodies An interface is like a class in which you forgot to declare the fields and left out the method bodies

Default Methods A default method is an instance method defined in an interface whose method header begins with the default keyword It also provides a code body Every class that implements the interface inherits the interface's default methods but can override them public interface Addressable { String getStreet(); String getCity(); default String getFullAddress() return getStreet() + ", " + getCity(); } An interface is like a class in which you forgot to declare the fields and left out the method bodies

Implementing an Interface Classes may declare that they “implement” an interface Given interface Doable a class Henway can implement it… public class Henway implements Doable { … } All the methods declared in Doable must appear in Henway (and other methods may appear, too)

Example: Doable interface Doable { int compute(int x); void doit(int y); } class Henway implements Doable { public int compute(int x) { return x + 1; public void doit(int y) { System.out.println(y);

Fields in Interfaces Interfaces may include fields Fields are implicitly declared public, final, and static That is, fields in interfaces are constants, and so must be declared with an initializer (=) Allows easy use of shared constants Methods are implicitly declared public See Booyah.java for example.

Example: Constants interface Constants { double X = 1234.56; int Y = -1; String Z = "hello there"; } public class Booyah implements Constants { public static void main(String[] args) { System.out.println(X); System.out.println(Y); System.out.println(Z); Point out that due to the way Java compiles dependent files, if you change the Constants interface by modifying one of the value, all the classes that implement that interface will be recompiled and so get the new values.

Implementing Multiple Interfaces A class can implement multiple interfaces The methods implemented are the union of the methods specified in the interfaces Examples: class SoapOpera implements Cryable { … } class SitCom implements Laughable { … } class Movie implements Laughable, Cryable { … }

Example: Rideable Rideable defines an interface to something you ride: void mount(); void dismount(); void move(boolean forward); void turn(int direction); void setSpeed(double mph); Implementations: class Motorcycle implements Rideable { … } class Horse implements Rideable, Trainable { … } class Bicycle implements Rideable { … } As another example: We might have an interface Trainable that is used for animals that can be trained. In that case, Horse would implement both Rideable and Trainable interfaces.

Example: Building a Game Problem: Implement a turn-based game in which players can pick up valuable objects Multiple players, each with own strategy Rules enforced by game controller Use of Java interface: Each player class implements Player interface Game controller expects parameters of type Player Main program: Creates player objects from classes Creates game controller with player objects Starts game controller Prints results Draw the picture on the next slide while going through this slide. Project 5 will be based on this design.

Game Program Class Diagram (rules and logic) uses creates Player (interface) Main (start up) implements creates Player 1 (strategy 1) Player 2 (strategy 2)

Player Interface interface Player { void makeMove(); void getItems(); } Any class can be a Player by implementing the method makeMove. The Game controller communicates with the Player classes through the makeMove() method, calling upon the Player strategy to make its move. With the interface approach, the Game controller doesn’t need to “know” what the actual class of the Player is only, that it implements (in this case) the makeMove() method.

Dragon Class public class Dragon implements Player { public void makeMove() {…}; public void getItems() {…}; …other methods… } By implementing the Player interface, this class is declaring that it can communicate with a game controller. Obviously, the Player1 class will likely have a number of other methods to carry out its tasks, but those methods are not directly accessible by the Game controller, which knows only about the makeMove() method.

Butterfly Class public class Butterfly implements Player { public void makeMove() {…}; public void getItems() {…}; …other methods… }

Main Class public class Main { public static void main(String[] args) { Dragon bob = new Dragon(); Butterfly ann = new Butterfly(); Game game = new Game(bob, ann); game.play(); System.out.println("game over"); } Note that it is the Main class only that knows the actual classes of the Player strategies. It passes objects to the Game class, but the Game class only knows about the Player interface, so only the methods defined in that interface.

Game Class public class Game { private Player p1; private Player p2; Game(Player p1, Player p2) { this.p1 = p1; this.p2 = p2; } void play() { p1.makeMove(); … p2.makeMove(); … p1.getItems(); … p2.getItems(); … Run the Main class in DrJava to show the (simple) output. The Game controller is started in two steps: (1) constructor that just keep track of things in the newly created Game object, and (2) the play() method that actually carries out the competition. Obviously, this example is greatly simplified. The play() method would be in a loop until the game completes. The Game class in general will have a lot of game state associated with it, e.g., the current deck of cards, pieces on the game board, dice state, hands held by the player characters, etc.

Example: Fibonacci Generator Write a class to generate the Fibonacci sequence Each value is sum of two previous values 1, 1, 2, 3, 5, 8, 13, 21, … Constructor takes an int n that specifies the (finite) number of values to generate Fibonacci object provides hasNext() and next() methods to generate the n values The hasNext() and next() methods are a useful idiom for iterating over a collection of objects or values. This decision to use hasNext() and next() is somewhat arbitrary on my part—it is done to fit in with the standard approach used in Java to iterate through data structures, e.g., the Scanner input stream.

Two Standard Java Interfaces (simplified) interface Iterator { boolean hasNext(); Object next(); void remove(); } interface Iterable { Iterator iterator(); Better write these both out on the chalkboard to for future discussion. These interfaces are used heavily in Java collections.

Java for-each Loop Uses Iterable interface for (Tree t : list) { … } The list must implement the Iterable interface That is, it must have a method that returns an Iterator over elements of the collection Write this one down, too, with an arrow pointing to list saying that it is an Iterable. From here, develop the Fibonacci class in three stages: basic, implements Iterator, and implements Iterable.

Fibonacci (1) import java.util.Iterator; Import java.lang.Iterable; public class Fibonacci implements Iterator, Iterable { private int n; // how many Fibonacci numbers private int i; // how many so far private int f1, f2; // last two Fibonacci numbers generated public Fibonacci(int n) { this.n = n; i = 0; f1 = f2 = 1; } // method required by Iterable interface... public Iterator iterator() { return this;

Fibonacci (2) // method required by Iterator interface... public boolean hasNext() { return i < n; } public Integer next() { if (i == 0 || i == 1) { i++; return 1; int t = f1 + f2; f1 = f2; f2 = t; return t;

Fibonacci (3) // method required by Iterator interface... public void remove() { } public static void main(String[] args) { Iterator i1 = new Fibonacci(25); while (i1.hasNext()) System.out.printf("%d ", i1.next()); System.out.printf("\n"); Iterable i2 = new Fibonacci(30); for (Object i : i2) System.out.printf("%d ", (Integer) i);