Lecture 04 agenda Go over QT exam. Discuss OO How to discover objects, properties, and methods Tetris game Other examples.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Lecture 5: Interfaces.
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Road Map Introduction to object oriented programming. Classes
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Programming Languages and Paradigms Object-Oriented Programming.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Creating a class. Fields (instance variables) Fields are the data defined in the class and belonging to each instantiation (object). Fields can change.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
Java Implementation: Part 3 Software Construction Lecture 8.
The Java Programming Language
Exceptions: Checked versus Unchecked Exceptions.
Programming Languages and Paradigms Object-Oriented Programming.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Creating a class. Fields (instance variables) Fields are the data defined in the class and belonging to each instantiation (object). Fields can change.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Programming in Java CSCI-2220 Object Oriented Programming.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Introduction to Object-Oriented Programming Lesson 2.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Object Oriented Programming Session # 03.  Abstraction: Process of forming of general and relevant information from a complex scenarios.  Encapsulation:
Lecture 04 agenda Go over QT exam. Discuss OO How to discover objects, properties, and methods Tetris game Other examples.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Object-Oriented Programming Important step forward in programming because it allows you to model real world systems which is what programming is all about.
OOP Basics Classes & Methods (c) IDMS/SQL News
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
BY:- TOPS Technologies
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Lecture 04 agenda Go over QT exam.
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Java – Inheritance.
Quizz Results hw1 quizz mean std-dev
Elipses int... passed into method as int[]
Presentation transcript:

Lecture 04 agenda Go over QT exam. Discuss OO How to discover objects, properties, and methods Tetris game Other examples

Object-Oriented Programming Important step forward in programming because it allows you to model real world systems which is what programming is all about. You can think about your system in a way that is logical to humans (not machines).

Heap and Stack The Heap is an area of memory reserved for data that is created at runtime -- that is, when the program actually executes. A heap has a big-O of Log(n) insert and seek times. Objects live on the heap. In contrast, the stack is an area of memory used for data whose size can be determined when the program is compiled. Variables on the stack can be local and their life is extremely short and their memory can be reclaimed quickly.

Write a very simple application for a fictitious real-estate company that displays the houses it currently offers. Some of the data they'd like to display include; address, market-value, an image of the house, and if the house has been foreclosed. 1/ display all the houses to the console. 2/ Apply a 25% subprime crash on all of our houses. Then display all of our houses to the console. 3/ Determine the most expensive house and display it to the console. Note: All houses are by default for sale, and once they're sold, they are removed from the display list. There is plenty of other data, like: weeks on market, the owners of the house, cube footage, etc. that we don't care about for our simple app.

git remote -v git fetch origin lab04a git tech origin lab04c git checkout -b lab04a origin/lab04a git checkout -b lab04c origin/lab04c

Tetris is a game where the player is confronted with falling shapes called tetriminos. A tetrimino has seven variations; S, L, O, Z, J, I, and T. See for exact configurations. Tetriminos float down from the top of the gaming-environment. The starting column is random, but the tetrimino always starts at top row and floats downward propelled by a gravitational-force that increases with time. Likewise, the points awarded increase as the speed increases. The player can also see which tetrimino is on-deck, allowing him/her to place the current-tetrimino strategically. The player may rotate the tetrimino 90 degrees clock-wise while it is still floating, so long as the rotation does not cause the tetrimino to be out-of-bounds. The player may also laterally-move the tetrimino left or right. And finally, the player may force the tetrimino to free-fall. When the bottom of a tetrimino touches either the bottom of the gaming-environment or the top of the wall made of previously accumulated tetrimino blocks, then its blocks too become immediately integrated into the wall. This integration triggers a series of events which are described below: If the integration results in a wall with complete-rows, then those rows dissappear and the player is awarded points. A high-scoring "tetris" occurs when "I" is integrated vertically into a wall where 4 rows become complete --and then dissappear. Progressively smaller awards are provided for 3, 2, and 1 row completions. Once the integration occurs (and any row completions are finished) the on-deck tetrimino become the current tetrimino and a new tetrimino is randomly generated to be the on-deck one. The now current tetrimino begins its descent, and the cycle continues until the wall reaches 90% of the height of the gaming environment, at which point the game is over.

//generate a new on-deck-tetro //while wall is < 90% of game-environment height //on-deck becomes current and generate a new on-deck tetro //start current-tetro descent at random column //while current-tetro is floating //allow user to control floating tetro //if current-tetrimino touches wall (or bottom) //integrate //check for row completions and make rows dissappear //award any points //break //pull current down with gravity //game over

Creating a class

Members aka fields (instance variables) Fields are the data defined in the class and belonging to each instantiation (object). Fields can change value i.e. they're variable. If a field is not variable, then you should exclude it, or make it a constant (public final static). Any static member belongs to the CLASS -- only one. A field is private. This is what is meant by encapsulation. You are hiding all but the 'public interface' (not to be confused with Interface). There is NO limit as to how many instances (objects) of a class you can have; and often you will have more than one.

getters and setters public type getField() public void setField(Type typName) They are public! They form the 'public interface' of the class. Use IntelliJ to generate them for you.

Constructors Constructors are optional. If your class is just a static driver; i.e. it just has a static main method, then no need to instantiate it; and no need for constructor. If your class is a POJO (Plain Old Java Object) -- a class that models a real world object (noun) in your system, then it should have a constructor. House, Car, Person, etc. If you don't provide a constructor, a no-args constructor is provided automatically. You can, and often want, more than one constructor with different signatures. You call a constrcutor with the 'new' keyword.

Methods public non-static methods may be called from the implicit parameter of an object (once instantiated in memory space). public static methods may be called directly from the class -- WITHOUT the need to instantiate in memory. Example: public static void main(). Java doesn't instantiate your methods over and over, just the fields. The methods are compiled in the.class file, and only once.

style conventions don't use variable/reference names like x,y, i, and j. That's very difficult to read. The exception is a counter, and even then, it should look like this: nC. cntrl-alt-L will format your code with indents. Use it.

style conventions Example: x verus dPrice? Example: name or strFirstName Example: today or greToday Example countries or strCountries (append an s for collections, the type it contains should be first) Communicate meta-data! – prefix conveys type – prefix conveys variable or object reference (one and three letters in prefix respectively) – postFix 's' conveys data-structure or array

Model a system Object-oriented programming is about modeling a system. Write the problem out as requirements -- this will essentially be a math word problem (your favorite kind to solve!) Your computer objects map directly to real- world objects (nouns). Your methods map directly to real-world actions (verbs).

Write a very simple application for a fictitious real estate company that displays the houses it currently offers. Some of the data they'd like to display include; address, market_value, an image of the house, and if the house has been foreclosed. 1/ display all the houses to the console. 2/ Apply a 25% subprime-crash on all of our houses. Then display all of our houses to the console. 3/ Determine the most expensive house and display it to the console. Note: All houses are by default for sale, and one they're sold, they are removed from the display list. There is plenty of other data, like: weeks on market, the owners of the house, cube footage, etc. that we don't care about for our simple app.

Class Objects See statics example

Deep Copy Clone When you clone an object, you are copying the values stored in its fields If those fields are primitives, no problem If those fields are objects, you're simply copying the memory addresses of to those objects. See realestate example

Inheritance Every object in Java inherits from Object You can see this by keying: cntrl-H or cntrl- shift-alt-U in IntelliJ Your job as a programmer is to organize your classes into a hierarchy so that code is not duplicated. A superclass is LESS complex that a subclass A subclass is MORE complex that a superlcass

Inheritance When an object inherits, EVERYTHING from it's ancestry is inherited as well (only these members and methods are implicit – and therefore not visible in the subclass' code) Often, you will want to increase the complexity of the subclass, and create more members and more methods Sometimes, you will want to force a genetic modification by overriding methods Will always call the deepest overridden instance method.

Abstract If I have one or more abstract methods (signature only, no implementation) in my class, I must declare the class as abstract (you can also have zero abstract methods) Extending abstract classes forces the programmer to override abstract methods. Overriding is a genetic modification of the subclass' behavior. You can only instantiate concrete classes, you can never instantiate abstract classes (or interfaces).

Abstract If you can't instantiate abstract classes, then what are they good for? The answer is: polymorphism Store your subclass objects in a collection of superclass references (abstract or concrete) See employee example

Autoboxing Since Java5, Wrapper classes and primitives are interchangeable! Legal statements: Integer intMe = 67; //auto-box double dMe = new Double(6.214); //auto-un- box See autboxing example

Overlaoding methods Overlaoded methods are those in the same class that share the same name, BUT have a different signature. Very useful for constructors, but also certain methods Return type is not sufficient to differentiate a signature. > public Employee(){ } > public Employee(String strName){ } > public Employee(String strName, double dSalary) { } See employee.Student.java example

Overlaoding methods public void display(int nParam){} public void display(String strParam){} //ok public void display(String strOther){} //not public String display(int nParam){} //not public double display(String str, Date dat){} //ok

Overriding methods Overriden methods are those with the same signature of a method in the class' hierarchy is optional. It tells the compiler to check the signature and verify the overloading Very useful for polymorphism! If you extend an abstract class, you MUST override its abstract methods. Same with Interfaces if you implement them.

Overriding methods When called from a superclass reference, how does the VM determine which overloaded method to envoke. 1/ start at the object-level, if it's implemented, there, then call it. 2/ If not, crawl up the hierarchy until its implemented See employee example

The this keyword The this keyword refers to the implicit parameter. You may refer to the instantiated object from within your class this way, and it'll resolve to the memory address of the object during runtime. See employee.Executive.java example

The super keyword The super keyword refers to the implict parameter, but it calls superclass constructors and instance methods only. You will most often see this in constructors where you will want to call the superclass constructor. If you don't call super() explicitly, the no-arg constructor is called anyway. You may also see super in overriden methods when you want to evoke the superclass version of that method before or after yours. See employee.Manager.java example

VarArgs VarArgs, or Variable Arguments is a feature since Java5. It allows you to specify a variable number of arguments as the last parameter of a method VarArgs are treated as Arrays inside the method >public void display(int nParam, String... strParams){}//ok >public void display(int nParam, String str, double... dParams){} //ok >public void display(int... nParams, String str){} //NOT See varargs example

Command-line from IntelliJ Ever wonder what public static void main(String[] args) means? The args argument is an array of String that are passed into main if you call this method from the command-line. You may pass args into main, by going to Run || Edit configurations || Program arguments See commandline example

Interfaces Not to be confused with “public interface” which are all the public methods of your class. An interface is like an abstract class, but it has NO members. The best way to think about an interface is that it's a CONTRACT. You extend a superclass, and you implement an interface. You can NEVER instantiate an interface, but you can instantiate concrete classes and store those objects in interface references.

Interfaces Unlike C++, Java does not allow multiple inheritance, however, it does allow a class to implement multiple interfaces. When a class implements an interface, it MUST, by contract, override all the methods in the interface. What good are interfaces? The answer: polymorphism. Store a heterogeneous collection of objects in interface references, so long as all the objects implement the interface. You are guarantee that all the objects in that collection will be able to call the methods of the interface. See fight and race examples

Interfaces override examples

JavaDocs e/documentation/index html#examples va/index html Tools > Generate javaDocs