CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors.

Slides:



Advertisements
Similar presentations
JAVA Revision Lecture Electronic Voting System Marina De Vos.
Advertisements

1 Object-Oriented Programming OOP. 2 Object-oriented programming is a new paradigm for program development in which the focus is on the data instead of.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Road Map Introduction to object oriented programming. Classes
Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors.
Objects and Classes First Programming Concepts. 14/10/2004Lecture 1a: Introduction 2 Fundamental Concepts object class method parameter data type.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
CS 106 Introduction to Computer Science I 03 / 17 / 2008 Instructor: Michael Eckmann.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
Dale Roberts Object Oriented Programming using Java - Class Constructors Dale Roberts, Lecturer Computer Science, IUPUI Department.
Question of the Day  What card(s) must you flip to verify the following statement: Cards with a vowel on one side, have an even number on the other side.
Programming Languages and Paradigms Object-Oriented Programming.
Question of the Day  Write valid mathematical equation using: one addition operator (‘+’) one equality operator (‘=’)  Should have equal values.
Announcements  If you need more review of Java…  I have lots of good resources – talk to me  Use “Additional Help” link on webpage  Weekly assignments.
Announcements  If you need more review of Java…  I have lots of good resources – talk to me  Use “Additional Help” link on webpage  Weekly assignments.
CSC 212 – Data Structures Lecture 12: Java Review.
Introduction to Object-Oriented Programming
Question of the Day  What card(s) must you flip to verify the following statement: Cards with a vowel on one side, have an even number on the other side.
CSC 212 Object-Oriented Programming and Java Part 1.
Introduction to Java and Object-Oriented Programming AJSS Computer Camp Department of Information Systems and Computer Science Ateneo de Manila University.
Patterns in OCaml functions. Formal vs. actual parameters Here's a function definition (in C): –int add (int x, int y) { return x + y; } –x and y are.
OBJECTS AND CLASSES CITS1001. Concepts for this lecture class; object; instance method; parameter; signature data type multiple instances; state method.
Chapter 1 Object Orientation: Objects and Classes.
Question of the Day  On a game show you’re given the choice of three doors: Behind one door is a car; behind the others, goats. After you pick a door,
Announcements  If you need more review of Java…  I have lots of good resources – talk to me  Use “Additional Help” link on webpage  Weekly assignments.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
ECE122 Feb. 22, Any question on Vehicle sample code?
Object-Oriented Design CSC 212. Announcements This course is speeding up and we are starting new material. Please see me if you feel this is going too.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Introduction to Java Java Translation Program Structure
Generic Types  Recent release of Java added generics  Include type parameters in class definition  Like methods, parameters can change each time 
LECTURE 9: INTERFACES & ABSTRACT CLASSES CSC 212 – Data Structures.
CSC 212 Object-Oriented Programming and Java Part 2.
Object Oriented Programming with Java 03 - Introduction to Classes and Objects.
COMP 110 Worksheet review, debugger Luv Kohli September 29, 2008 MWF 2-2:50 pm Sitterson 014.
CSC 212 – Data Structures Lecture 2: Primitives, References, & Classes.
Problem of the Day How can you make 16 right angles using 4 matchsticks WITHOUT breaking any of them?
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Lecture 08. Since all Java program activity occurs within a class, we have been using classes since the start of this lecture series. A class is a template.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Types and Interfaces COMP.
CSC 212 – Data Structures Lecture 5: Variables. Problem of the Day Why do underground subway stations always have more escalators going up than down?
LECTURE 20: RECURSION CSC 212 – Data Structures. Humorous Asides.
Catie Welsh March 23,  Lab 6 due Friday by 1pm 2.
Looking inside classes Conditional Statements Week 4.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
COMP 110 Designing and overloading methods Luv Kohli November 3, 2008 MWF 2-2:50 pm Sitterson 014.
Computer Science II 810:062 Section 01 Session 2 - Objects and Responsibilities.
Today’s lecture Review chapter 5 go over exercises.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
AP Java Ch. 4 Review Question 1  Java methods can return only primitive types (int, double, boolean, etc).
Question of the Day completes starts  What word completes the 1 st word & starts the 2 nd one: DON???CAR.
Topics Instance variables, set and get methods Encapsulation
Question of the Day  Move one matchstick to produce a square.
CSC 212 – Data Structures Lecture 6: Static and non-static members.
CONDITIONALS CITS1001. Scope of this lecture if statements switch statements Source ppts: Objects First with Java - A Practical Introduction using BlueJ,
Problem of the Day  Why are manhole covers round?
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Class Definitions: The Fundamentals Chapter 6 3/30/15 & 4/2/15 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education.
Comp1004: Building Better Objects I Methods. Coming up Methods and Parameters – Why Parameterise? – Call by value, call by reference Return Types – Methods.
Lecture 3: Fields, Methods, & Constructors
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.
Lesson 2: Building Blocks of Programming
Building Java Programs
Chapter 14 Abstract Classes and Interfaces
Introduction to Object-Oriented Programming
Announcements Lab 5 was due today Program 3 due Monday by 12pm
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Day 11 The Last Week!.
Presentation transcript:

CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

Problem of the Day Why are manhole covers round? It is the only shape that guarantees that the cover cannot fall in!

Announcements Still need a note-taker; please see me if you are interested in the $50 If you feel this Java review is going too fast talk to me, check out the pages from the “Links” page, and/or seek out additional resources

Classes vs. Objects Classes are recipes or blueprints which describe a data type  Classes (usually) cannot do anything on their own Objects are the instances of the class  New object created (instantiated) by new  Fields describe object’s state  Methods represent object’s behavior

Fields Fields are defined by a class  All instances of class have same fields…  … but fields’ values may differ Fields in a class must have unique name  But same name okay if in different classes Definition must also include a data type  Can be primitive or reference type  Fields behave like variables of that type would

Class Example public class Car { /** * Name of company that made the car and name of the car model */ String makeAndModel; /** Color of the car. */ String color; /** How full the gas tank is, expressed as * a percentage. */ float tankLevel; /** Number of miles recorded on the odometer */ int odometerReading; /* Definition continues from here */

Using Fields (1) Car profHertzCar = new Car(); profHertzCar.makeAndModel = “BMW Z4”; profHertzCar.color = “Deep Green Metallic”; profHertzCar.tankLevel = 1.0; profHertzCar.odometerReading = 10000; Car shoshannaCar = new Car(); shoshannaCar.makeAndModel = “Ford Taurus Wagon”; shoshannaCar.color = “Silver”; shoshannaCar.tankLevel = ; shoshannaCar.odometerReading = ;

Using Fields (2) Car dreamCar = new Car(); dreamCar.makeAndModel = “BMW Z4”; dreamCar.color = “Deep Green Metallic”; dreamCar.tankLevel = 1.0; dreamCar.odometerReading = 10000; Car realCar = dreamCar; realCar.makeAndModel = “Ford Taurus Wagon”; realCar.color = “Silver”; realCar.tankLevel = ; realCar.odometerReading = ;

Methods All Java code is defined within a class Define actions & behavior of objects  Also specify how object’s state should change Methods must have unique name and parameter list (“signature”)  Two methods can share name Methods also define return type  Return type is not part of signature, however

Method Return Types Return type could be a primitive, reference, array, or void  void methods cannot return data  Other methods must return data Method immediately stops at return Will not compile if:  Code continues after return  Possible to end non-void method without`` return

Car Example /** Reset the fuel tank to be full. */ void fillTank() { tankLevel = 1.0; } /** * Change the amount of fuel by some means levelDelta Change in fuel level (as % of tank capacity) */ void adjustFuel(float levelDelta) { tankLevel += levelDelta; /* Check that the tank level makes sense. */ if (tankLevel > 1.0) { tankLevel = 1.0; } else if (tankLevel < 0.0) { tankLevel = 0.0; } }

/** * Drive around town and look for the hot spots to hit. distance Number of miles traveled gasUsed Amount of fuel used on this trip */ void crusin(int distance, float gasUsed) { int newDistance = odometerReading + distance; adjustFuel(gasUsed); odometerReading = newDistance; } /** * Find out if the car will start. Assumes that you will not * hotwire the car. haveKey True if we the key to this car; else it is false True if the engine would start, false otherwise */ boolean willStart(boolean haveKey) { if (!haveKey || tankLevel == 0.0) { return false; } else if (makeAndModel.startsWith(“Jaguar”)) { java.util.Random rnd = new Random(); return rnd.nextBoolean(); } else { return true; } }

Using Methods Car dreamCar = new Car(); Car realCar = dreamCar; dreamCar.makeAndModel = “BMW Z4”; dreamCar.color = “Deep Green Metallic”; dreamCar.tankLevel = 1.0; dreamCar.odometerReading = 10000; if (dreamCar.willStart(true)) { System.out.println(“Vroom vroom”); } realCar.crusin(400, -1.0); if (dreamCar.willStart(true)) { System.out.println(“Vroom vroom”); } else { System.out.println(“*sigh*”); }

Constructors Special methods called only when instantiating an object  Must have identical name as class  Cannot include a return type (include void)  Can define multiple constructors with different signatures Parameters used in new must match at least 1 constructor

Car Example /** * Create a new car with the given make, model, color and tankLevel. make Manufacturer of the car being created model Model of the car being instantiated color Color to which the car should be painted pctFull How full the gas tank is (in % of capacity terms) */ Car(String make, String model, String color, float pctFull) { // Set car’s make and model makeAndModel = make + “ “ + model; // Record the color this.color = color; // Set the tank level adjustFuel(pctFull); // New cars have not driven anywhere, yet this.odometerReading = 0; }

Using Constructors Car profHertzCar = new Car(); profHertzCar.makeAndModel = “BMW Z4”; profHertzCar.color = “Deep Green Metallic”; profHertzCar.tankLevel = 1.0; profHertzCar.odometerReading = 10000; Car profHertzCar = new Car(“BMW”, “Z4”, “Deep Green Metallic”, 1.0); profHertzCar.odometerReading = 10000; /* This causes an error, since there is not a constructor that takes two String parameters. */ Car badCar = new Car(“BMW”, “Z4”);

Before Next Lecture… Finish week #1 homework Wednesday’s lecture will continue with constructors, fields, & methods  Keep thinking & ask any questions you have  May want to review any old notes & handouts