CS/ENGRD 2110 Fall 2018 Lecture 5: Local vars; Inside-out rule; constructors http://courses.cs.cornell.edu/cs2110.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
Access to Names Namespaces, Scopes, Access privileges.
Java boot camp1 Subclasses Concepts: The subclass and inheritance: subclass B of class A inherits fields and methods from A. A is a superclass of B. Keyword.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
COMP More About Classes Yi Hong May 22, 2015.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
CS/ENGRD 2110 FALL 2013 Lecture 5: Local vars; Inside-out rule; constructors 1.
1 Biggest issue!!! You can’t do questions on this topic correctly unless you draw variables, draw objects when they are created, and draw frames for method.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
CS/ENGRD 2110 SPRING 2012 Lecture 2: Objects and classes in Java 1.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
CS100A, Fall 1998 Key Concepts 1 These notes contain short definitions of the basic entities that make up a Java program, along with a description of the.
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,
CIT 590 Intro to Programming Lecture 13. Some Eclipse shortcuts CTRL + SHIFT + F – format file (proper indentation etc). Please do this before you submit.
1 CS September 2008 Discussion of Methods: Executing method calls.If-statements. The return statement in a function. Local variables. For this and.
CS100A, 15 Sept Lecture 5 1 CS100A, 5 Sept This lecture continues the discussion of classes. The important new concept of this lecture is.
CS/ENGRD 2110 SPRING 2016 Lecture 2: Objects and classes in Java 1.
CS100A, Fall Lecture 5 1 CS100A, Fall 1997 Lecture, Tuesday, 16 September. This lecture continues the discussion of classes. The important new concept.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
1 CS1110 Thursday, 10 Feb 2011 Discussion of Methods: Executing method calls. If-statements. The return statement in a function. Local variables. For this.
1 CS February 2009 Inside-out rule; use of this and super Developing methods (using String ops). Read sec. 2.5 on stepwise refinement Listen to.
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
1. Understanding the execution of local variable declaration (in a method body) new expression ( 3 steps ) method call (method frames, call stack) examples.
Defining Your Own Classes II
More on Arrays Review of Arrays of ints, doubles, chars
CS/ENGRD 2110 Fall 2017 Lecture 2: Objects and classes in Java
Topic: Classes and Objects
The need for Programming Languages
Recitation 2 Exception handling.
Some Eclipse shortcuts
CS/ENGRD 2110 Spring 2014 Lecture 5: Local vars; Inside-out rule; constructors
Review Session.
Chapter 5 Hierarchies IS-A associations superclasses subclasses
CS/ENGRD 2110 Spring 2018 Lecture 2: Objects and classes in Java
CS 302 Week 11 Jim Williams, PhD.
CS/ENGRD 2110 Spring 2018 Lecture 5: Local vars; Inside-out rule; constructors
Chapter 9 Inheritance and Polymorphism
CS/ENGRD 2110 Spring 2017 Lecture 5: Local vars; Inside-out rule; constructors
Class Structure 16-Nov-18.
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Java Programming Language
Overloading and Overriding
CS/ENGRD 2110 Fall 2017 Lecture 5: Local vars; Inside-out rule; constructors
CS/ENGRD 2110 Spring 2016 Lecture 5: Local vars; Inside-out rule; constructors
Sit next to someone. Today, we do some work in pairs.
Class Structure 7-Dec-18.
Class Structure 2-Jan-19.
CS/ENGRD 2110 Fall 2018 Lecture 2: Objects and classes in Java
Sit next to someone. Today, we do some work in pairs.
Recap Week 2 and 3.
CS/ENGRD 2110 Spring 2019 Lecture 2: Objects and classes in Java
Class Structure 25-Feb-19.
CS/ENGRD 2110 Spring 2019 Lecture 5: Local vars; Inside-out rule; constructors
Chapter 11 Inheritance and Polymorphism Part 1
CS/ENGRD 2110 Spring 2019 Lecture 2: Objects and classes in Java
Chapter 11 Inheritance and Encapsulation and Polymorphism
CS 240 – Advanced Programming Concepts
Inheritance and Polymorphism
Presentation transcript:

CS/ENGRD 2110 Fall 2018 Lecture 5: Local vars; Inside-out rule; constructors http://courses.cs.cornell.edu/cs2110

Announcements A1 is due tomorrow If you are working with a partner: form a group on CMS & submit once A2 is out. Remember to get started early! Because of Jewish holidays, the due date for A2 has been changed to Sunday, 16 September. ONLY TWO DAYS OF LATENESS ALLOWED. Last day to submit is 18 September. Next week's recitation is on testing. No tutorial/quiz this week!

Example Constructor: Person Class public class Person { private String firstName; //cannot be null private String lastName; /** Create a person with the given names. */ public Person(String f, String l) { assert f != null; firstName= f; lastName= l; } Constructor: Initializes fields to make class invariants true

Adding a Middle Name Option (v1) public class Person { private String firstName; //cannot be null private String middleName; private String lastName; public Person(String f, String l) { assert f != null; firstName= f; lastName= l; } public Person(String f, String m, String l) { middleName= m; 👍🏽 or 👎 ? Want to change body to call first constructor

Adding a Middle Name Option (v2) public class Person { private String firstName; //cannot be null private String middleName; private String lastName; public Person(String f, String l) { assert f != null; firstName= f; lastName= l; } public Person(String f, String m, String l) { this(f, l); middleName= m; Looks a little weird, but it saves you from changing your code when you change the name of the class. Use this (not Person) to call another constructor in the class. Must be first statement in constructor body!

Too Busy for Constructors? Java makes one! public class Person { private String firstName; //cannot be null private String lastName; public String toString() { return firstName + “ ” + lastName;} } Person p= new Person(); public Person() {}; 👍🏽 or 👎 ?

Wow, every class has an empty Constructor? public class Person { private String firstName; //not null private String middleName; private String lastName; public Person(String f, String l) { assert f != null; firstName= f; lastName= l; } public Person(String f, String m, String l) { this(f, l); middleName= m; Person p= new Person(); Nope! Syntax Error: No constructor in Person matches this invocation Arguments: () Expected return type: Person Candidate signatures: Person(String, String) Person(String, String, String)

Which toString is called? public class Person { private String firstName; private String lastName; public Person(String f, String l) { assert f != null; firstName= f; lastName= l; } public String toString() { return firstName + “ ” + lastName; Person p1= new Person(“Grace”, “Hopper”); p1.toString(); p1 Person@20 Person@20 toString() Object firstName “Grace” lastName “Hopper” toString() Person

Constructing with a Superclass Cornellian@a0 Object firstName lastName toString() Person Cornellian netID null public class Cornellian extends Person { private String netID; /** Constructor: Person with a netID. */ public Cornellian(String f, String l, String id) { super(f, l); netID= id; } new Cornellian("David", "Gries", “djg17”); "David" "Gries" Use super (not Person) to call superclass constructor. Before next slide, make these changes, then override toString in PhD and use super.toString(). Must be first statement in constructor body! djg17

Not Feeling Super? Java thinks you are! public class Cornellian extends Person { private String netID; /** Constructor: Person with a netID. */ public Cornellian(String f, String l, String id) { netID= id; } new Cornellian("David", "Gries", “djg17”); super(); If first statement in constructor body is not a constructor call, Java inserts super(); for you! Before next slide, make these changes, then override toString in PhD and use super.toString(). 👍🏽 or 👎 ?

More about super Within a subclass object, super refers to the partition above the one that contains super. Cornellian@a0 Object firstName lastName toString() Person Cornellian netID "David" "Gries" djg17 Because of keyword super, the call toString here refers to the Person partition. "super" refers to the partition in the object that's directly above the current one. toString() { return super.toString() + “ ” +netID; }

Without OO … Without OO, you would write a long involved method: public double getName(Person p) { if (p is a CornellUndergrad) { … } else if (p is a CornellFaculty) else if (p prefers Cornellian) else … } OO eliminates need for many of these long, convoluted methods, which are hard to maintain. Instead, each subclass has its own getName. Results in many overriding method implementations, each of which is usually very short

Local variables middle(8, 6, 7) /** Return middle value of a, b, c (no ordering assumed) */ public static int middle(int a, int b, int c) { if (b > c) { int temp= b; b= c; c= temp; } if (a <= b) { return b; return Math.min(a, c); } Parameter: variable declared in () of method header Local variable: variable declared in method body a 8 c 7 b 6 temp ? All parameters and local variables are created when a call is executed, before the method body is executed. They are destroyed when method body terminates.

Scope of local variables /** Return middle value of a, b, c (no ordering assumed) */ public static int middle(int a, int b, int c) { if (b > c) { int temp= b; b= c; c= temp; } if (a <= b) { return b; return Math.min(a, c); } block Scope of local variable (where it can be used): from its declaration to the end of the block in which it is declared. Every pair of curly braces defines a block.

Scope In General: Inside-out rule Inside-out rule: Code in a construct can reference names declared in that construct, as well as names that appear in enclosing constructs. (If name is declared twice, the closer one prevails.) /** A useless class to illustrate scopes*/ public class C{ private int field; public void method(int parameter) {      if (field > parameter) {          int temp= parameter;      } } class method block

Principle: declaration placement /** Return middle value of a, b, c (no ordering assumed) */ public static int middle(int a, int b, int c) { int temp; if (b > c) { temp= b; b= c; c= temp; } if (a <= b) { return b; return Math.min(a, c); } 👍🏽 or 👎 ? Not good! No need for reader to know about temp except when reading the then-part of the if- statement Demo after this slide: show moving the point where temp was declared. Principle: Declare a local variable as close to its first use as possible.

Poll time! What 3 numbers are printed? public class ScopeQuiz {   private int a;   public ScopeQuiz(int b) {     System.out.println(a);     int a= b + 1;     this.a= a;     a= a + 1;   }   public static void main(String[] args) {     int a= 5;     ScopeQuiz s= new ScopeQuiz(a);     System.out.println(s.a); } A: 5, 6, 6 B: 0, 6, 6 C: 6, 6, 6 D: 0, 6, 0