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.

Slides:



Advertisements
Similar presentations
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Advertisements

Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Road Map Introduction to object oriented programming. Classes
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading:
CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors.
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.
Applications in Java Towson University *Ref:
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
CSC 212 Object-Oriented Programming and Java Part 1.
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.
1 CSC 221: Computer Programming I Spring 2010 interaction & design  modular design: roulette game  constants, static fields  % operator, string equals.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
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,
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,
Problem of the Day  Why are manhole covers round?
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.
Question of the Day You overhear a boy & his mother talking: Mom:What is ? Boy: That's easy, 33. Mom: Good. What's ? Boy:Simple. It's 40. Mom:Excellent!
ECE122 Feb. 22, Any question on Vehicle sample code?
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
 The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
RECITATION 4. Classes public class Student { } Data Members public class Student { private String name; public String id; }
1 Enumerations and Structs Chapter 9. 2 Objectives You will be able to: Write programs that define and use enumeration variables. Write programs that.
Question of the Day You overhear a boy & his mother talking: Mom:What is ? Boy: That's easy, 33. Mom: Good. What's ? Boy:Simple. It's 40. Mom:Excellent!
Question of the Day  Thieves guild states it will sell to members: lock picking kits  $0.67 each 40’ rope  $2.12 each Wire cutters  $4.49 each How.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Question of the Day  Thieves guild states it will sell to members: lock picking kits  $0.67 each 40’ rope  $2.12 each Wire cutters  $4.49 each How.
CSC 212 Object-Oriented Programming and Java Part 2.
CSC 212 – Data Structures Lecture 2: Primitives, References, & Classes.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
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.
CSC 212 – Data Structures Lecture 5: Variables. Problem of the Day Why do underground subway stations always have more escalators going up than down?
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Question of the Day You overhear a boy & his mother talking: Mom:What is ? Boy: That's easy, 33. Mom: Good. What's ? Boy:Simple. It's 40. Mom:Excellent!
1 Class and Object Lecture 7. 2 Classes Classes are constructs that define objects of the same type. A Java class uses instance variables to define data.
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
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
CSC 212 – Data Structures Lecture 6: Static and non-static members.
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
Problem of the Day  Why are manhole covers round?
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
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.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Question of the Day  How do you add 5 matches to these 6 & make 9?
Defining Your Own Classes II
Lecture 3: Fields, Methods, & Constructors
Java Primer 1: Types, Classes and Operators
Java Programming Language
Implementing Non-Static Features
Building Java Programs
Chap 1 Chap 2 Chap 3 Chap 5 Surprise Me
Building Java Programs
Java Programming Language
Introduction to Object-Oriented Programming
Corresponds with Chapter 5
Previous Lecture: Today’s Lecture: Reading (JV):
Presentation transcript:

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. A A B B

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. A A B B

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 problems due before class  Remove rust from summer and get back into coding  Problems designed to help learn new material, too

Classes vs. Objects  Classes are blueprints describing data type  Classes (usually) cannot do anything on their own  Objects are instances of a class  New objects created (instantiated) using new  Fields describe state of an object  Object’s behavior represented by methods

Instance Variables  All of class's instances have same fields…  … but values can differ between each instance  In a class, each field must have unique name  Different classes can duplicate names of fields  Field declaration also includes data type  Will act like variables of that type  Can be primitive, enum, or reference type

Class Example public class Car { /** What kind of car & who made it */ private String makeAndModel; /** Color of the car. */ private String color; /** Percent full the gas tank is */ private float tankLevel; /** Miles recorded on the odometer */ private 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 actualCar = new Car(); actualCar.makeAndModel = “Subaru Outback"; actualCar.color = “Brown”; actualCar.tankLevel = ; actualCar.odometerReading = 47634;

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

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 = “Subaru Outback”; realCar.color = “Silver”; realCar.tankLevel = ; realCar.odometerReading = 45634;

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 = “Subaru Outback”; realCar.color = “Silver”; realCar.tankLevel = ; realCar.odometerReading = 45634;

Methods  Define how objects act, behave, & change  Need unique name & parameters (“signature”)  Can share name or parameter list, but not both  Determines which code used at any method call  Methods also define return type  Return type is not part of signature  Cannot help determine which method to call

Method Return Types  Can be primitive, reference, array, or void  void methods cannot return data  All other methods must return data  Method execution stops immediately at return  Will NOT execute further in method  After return, calling method executes immediately  Compilation error occurs when:  Method includes executing code after return  Non- void method can end without return statement

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

Useful Car Methods void crusin(int distance, float gasUsed) { int newDistance = odometerReading + distance; adjustFuel(gasUsed); odometerReading = newDistance; } 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; } }

Calling Methods Car dreamCar = new Car(); 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”); } dreamCar.crusin(400, 1.0); if (dreamCar.willStart(true)) { System.out.println(“Vroom vroom”); } else { System.out.println(“*sigh*”); }

Constructors  Special methods called to instantiate object  Have identical name as class  No return type (not even void ) allowed  If parameters differ, multiple constructors possible  Parameters to new must match 1 constructor  If no constructor defined, implicit one used for class  No parameters included in implicit constructor

Tracing with Objects public class Account { public String own; public float bal; public String id; Account check = new Account(“haxx0r”, 1.25, “0001”); Account richOne = new Account(“billG”, ,“2408”); check.bal -= 1.20; // Bought a coffee check.id = “2408”; // 1 st theft attempt richOne.own = “haxx0r”; // 2 nd theft attempt

Tracing Parameters  Traced like variable created at method call  New variable created each time method called  Variable lives until completion of method  Initialized with value of argument  Works like ran parameter = actual  Primitives copy value into parameter  Parameter is aliased if a reference

Tracing Parameters public void badTransfer(Account src,float amt){ if (amt >= src.bal) { amt = src.bal (); src = null; } else { src.bal -= amt; } bal += amt; } check.badTransfer(richOne, Float.MAX_VALUE);

Locals  Variables declared inside a method  Must be assigned value before using  “Live” only for code block in which declared  Local always better than instance variable  Easy trick to simplify design, algorithm, & code  Reduces opportunities for bugs dramatically  Added bonus, creates fewer comments to write!  Declare local in smallest enclosing block

Locals  Variables declared inside a method  Must be assigned value before using  “Live” only for code block in which declared  Local variable always better than field  Easy trick to simplify design, algorithm, & code  Reduces opportunities for bugs dramatically  Added bonus, creates fewer comments to write!  Declare local in smallest enclosing block Never declare a field when a local will do

Locals  Variables declared inside a method  Must be assigned value before using  “Live” only for code block in which declared  Local variable always better than field  Easy trick to simplify design, algorithm, & code  Reduces opportunities for bugs dramatically  Added bonus, creates fewer comments to write!  Declare local in smallest enclosing block

Locals  Variables declared inside a method  Must be assigned value before using  “Live” only for code block in which declared  Local variable always better than field  Easy trick to simplify design, algorithm, & code  Reduces opportunities for bugs dramatically  Added bonus, creates fewer comments to write!  Declare local in smallest enclosing block

Locals  Variables declared inside a method  Must be assigned value before using  “Live” only for code block in which declared  Local variable always better than field  Easy trick to simplify design, algorithm, & code  Reduces opportunities for bugs dramatically  Added bonus, creates fewer comments to write!  Declare local in smallest enclosing block

Locals  Variables declared inside a method  Must be assigned value before using  “Live” only for code block in which declared  Local variable always better than field  Easy trick to simplify design, algorithm, & code  Reduces opportunities for bugs dramatically  Added bonus, creates fewer comments to write!  Declare local in smallest enclosing block

Calling Methods  Some methods really need an object  Integer. intValue() is unclear without an object  But other methods independent of an instance  main(String[]) lacks an object to use to call it  Why need Integer to call parseInt(String) ?

static Methods  static methods do not need an instance  Behavior defined by class, not an instance  parseInt(String) based only on Integer  All methods similar in how written & executed  May or may not include parameters  Local variables can be declared and used  Must either be void or declare return type  Mix of methods possible for all classes & enums

Making Method static  Include static keyword in method declaration public static void main(String args[]) public static int parseInt(String s) private static int nextInt()  Behaves like any other method (almost)  Use locals & parameters like normal  As with other code, call (nearly all) other methods  Java operators can be used  Perform any I/O operations

static v. Non- static  Methods that are non- static have this  Aliased to instance on which method called  Can directly use fields & call all methods  No this parameter in static methods  Code directly using non- static members illegal…  … using static fields & methods perfectly legal  As always, can use object to access its members

BadDuck public class BadDuck { private int quackVolume; public static void printVolume() { System.out.println(“Volume is ” + getVolume()); BadDuck duck = new BadDuck(); duck.quackVolume = 11; System.out.println(“Volume is ”+duck.getVolume()); } public int getVolume() { return quackVolume; } }

BadDuck getVolume() public class BadDuck { private int quackVolume; public static void printVolume() { System.out.println(“Volume is ” + getVolume()); BadDuck duck = new BadDuck(); duck.quackVolume = 11; System.out.println(“Volume is ”+duck.getVolume()); } public int getVolume() { return quackVolume; } } Compiler error. Without an object, whose volume are we getting?

BadDuck getVolume() public class BadDuck { private int quackVolume; public static void printVolume() { System.out.println(“Volume is ” + getVolume()); BadDuck duck = new BadDuck(); duck.quackVolume = 11; System.out.println(“Volume is ”+duck.getVolume()); } public int getVolume() { return quackVolume; } } This is good. There is a duck to get the volume.

BadDuck public class BadDuck { public static String duckSpeak() { return “quack”; } } public class UseDuck { public void speak() { System.out.println(BadDuck.duckSpeak()); BadDuck duck = new BadDuck(); System.out.println(duck.duckSpeak()); } }

BadDuck public class BadDuck { public static String duckSpeak() { return “quack”; } } BadDuck.duckSpeak() public class UseDuck { public void speak() { System.out.println(BadDuck.duckSpeak()); BadDuck duck = new BadDuck(); System.out.println(duck.duckSpeak()); } } This compiles. Static methods do not use an object, so this is preferred way to call them.

BadDuck public class BadDuck { public static String duckSpeak() { return “quack”; } } duck.duckSpeak() public class UseDuck { public void speak() { System.out.println(BadDuck.duckSpeak()); BadDuck duck = new BadDuck(); System.out.println(duck.duckSpeak()); } } Also fine, but since method is static, still cannot access instance.

static Fields  Some data belongs to class, not instance Float.MAX_VALUE Citizen.nationalPopulation Instructor.bestProfessor  static fields used for any class-based data  All of the class instances see same value  Do not need an instance to access this value  Can be updated via any instance or via class

static Code for Tracing public class Player { private static int num; private static String champ; private String name; public Player(String newN) { num += 1; name = newN; } public static int getPlayers() { return num; } public static String setChamp(String best) { champion = best; } }

Tracing With Statics public void startGame() { Player player1, player2, player3; player1 = new Player(“Homer”); player2 = new Player(“Joey JoJo”); player3 = player2; Player.champ = “Homer”; player2.setChamp (“Joey JoJo”); }

static v. non- static Review  Difference between static & non- static  static members belong to the class  Accessing & using member possible without instance  Methods lack implicit this parameter no matter what  Instances required for non- static member  Fields’ data instance-specific and not shared by class  Can access all members using implicit this parameter

Your Turn  Get into your groups and complete activity

For Next Lecture  Keep reviewing your Java lessons  Will be doing some fun & different problems Monday  Really need to be back up-to-speed at that point  There is weekly assignment problem on Angel  Due before Monday’s lecture (via )  With this finish removing rust from lazy summer