Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS

Slides:



Advertisements
Similar presentations
COMP 110: Introduction to Programming Tyler Johnson Mar 16, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Advertisements

1 CSE 331 Enumerated types ( enum ) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Basic -2 Classes and Objects. Classes and Objects A class is a complex data TYPE An object is an instance of a class. Example: Class: Person Objects:
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Intro to CS – Honors I Class Types and Object References GEORGIOS PORTOKALIDIS
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Intro to CS – Honors I Inheritance and Polymorphism GEORGIOS PORTOKALIDIS
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
Road Map Introduction to object oriented programming. Classes
Chapter 3 Classes and Methods. 2 Knowledge Goals Appreciate the difference between a class in the abstract sense and a class as a Java construct Know.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Constructors. Defining Constructors  A constructor is a special kind of method that is designed to perform initializations, such as giving values to.
Information Hiding and Encapsulation
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Java Classes Introduction and Chapter 1 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
Intro to CS – Honors I Classes and Methods GEORGIOS PORTOKALIDIS
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
SWE 510: Object Oriented Programming in Java1 Defining Classes 1 This slide set was compiled from the Absolute Java textbook and the instructor’s own class.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Lecturer: Dr. AJ Bieszczad Chapter 5 COMP 150: Introduction to Object-Oriented Programming 5-1 l Programming with Methods l Static Methods and Static Variables.
10-Nov-15 Java Object Oriented Programming What is it?
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
CSC 142 Computer Science II Zhen Jiang West Chester University
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, Stack and Heap When your program is running, some memory is used to store local variables.
Catie Welsh March 23,  Lab 6 due Friday by 1pm 2.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Polymorphism l Constructors.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CPSC 233 Tutorial 5 February 9 th /10 th, Java Classes Each Java class contains a set of instance variables and methods Instance Variables: Type.
Java Classes Introduction. Contents Introduction Objects and Classes Using the Methods in a Java Class – References and Aliases Defining a Java Class.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
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.
More About Objects and Methods
Classes and Objects 2nd Lecture
Computer Science II Exam 1 Review.
Object Based Programming
Classes and Objects: Encapsulation
Classes and Objects Encapsulation
Defining Classes and Methods
Extending Classes.
Implementing Non-Static Features
Java Classes and Objects 3rd Lecture
More About Objects and Methods
Java Programming Language
Announcements Lab 5 was due today Program 3 due Monday by 12pm
More About Objects and Methods Chapter 5 Programming with Methods
OO Programming Concepts
slides created by Ethan Apter and Marty Stepp
CMSC 202 Encapsulation Version 9/10.
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
More About Objects and Methods Chapter 5 Programming with Methods
Presentation transcript:

Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS

A Methods Heading Defining a method requires the following ReturnType MethodName(Type Parameter, Type Parameter, …) The method name, number of parameters, and their type constitutes a methods signature MethodName(Type Parameter, Type Parameter, …) A primitive or class type, or void 0 or more paremeters A methods heading A methods signature

Overloading Methods Java allows you to define multiple methods with the same name and different signatures class MyDate { private int year, month, day; public void setDate(int newYear, int newMonth, int newDay) { this.year = newYear; this.month = newMonth; this.day = newDay; } public void setDate(int newYear, int newMonth) { this.year = newYear; this.month = newMonth; this.day = -1; // So we know it was not set } public void setDate(int newYear) { this.year = newYear; this.month = -1; // So we know it was not set this.day = -1; } Same method name different number of arguments

Overloading Methods Java allows you to define multiple methods with the same name and different signatures class MyString { private String string; public void append(int integer) { string += integer; } public void append(String subString) { string += subString; } public void append(float floatNumber) { string += floatNumber; } public void append(double doubleNumber) { string += doubleNumber; } Same method name, same number of arguments, different types

Overloading Methods Java allows you to define multiple methods with the same name and different signatures class MyString { private String string; public void append(int integer) { string += integer; } public void append(String subString) { string += subString; } public void append(float floatNumber) { string += floatNumber; } public void append(double doubleNumber) { string += doubleNumber; } Same method name, same number of arguments, different types

Overloading and Automatic Type Casting Java automatically casts types when they fit byte short int long float double MyString str = new MyString(); byte data = 10; str.append(data); Which method will be picked? class MyString { private String string; public void append(int integer) { string += integer; } public void append(String subString) { string += subString; } public void append(float floatNumber) { string += floatNumber; } public void append(double doubleNumber) { string += doubleNumber; }

Ambiguous Overloading Certain declaration of parameter types may lead to ambiguous overloading SampleClass.problemMethod(5, 10); Which method will be picked? These however work SampleClass.problemMethod(5.0, 10); SampleClass.problemMethod(5, 10.0); public class SampleClass { public void problemMethod(double n1, int n2)... public void problemMethod(int n1, double n2)... Overloading is done before automatic type casting

The Return Type Is Not Used for Overloading The return type of a method is not part of its signature public class Pet { public float getWeight()... public double getWeight()... You cannot overload based on the return type These routines cannot be declared in the same class

Things to Remember About Overloading A methods name, the number of its parameters, and their type define its signature Overloading allows you to define multiple methods with the same name and different signature Overloading is done before trying automatic type conversion Use overloading only when you have to

Constructors Special methods that are invoked when you create a new object Species earthSpecies = new Species(); You can change how the objects instance variables are initialized by defining your own constructors Only called when allocating an object You cannot call it with an existing object They can also take parameters They have the name of the class They do not have a return type Not even void! Allocate new object and invoke the Species() constructor - name: String - population: int - growthRate: double Species + setSpecies(String newName, int newPopulation, double newGrowthRate): void + getName(): String + getPopulation(): int + getGrowthRate( ): growthRate + writeOutput(): void If none were defined, Java will create a default constructor that initializes the objects instance variables with default values

Example of Constructors public class Pet { private String name; private int age; //in years private double weight;//in pounds public Pet() { name = "No name yet."; age = 0; weight = 0; } public Pet(String initialName, int initialAge, double initialWeight) { name = initialName; if ((initialAge < 0) || (initialWeight < 0)) { System.out.println("Error: Negative age or weight."); System.exit(0); } else { age = initialAge; weight = initialWeight; }... A constructor without parameters is the default constructor No return type Constructors can also be overloaded

Skipping the Default Constructor Creating a new object without a default constructor fails MyDate date = new MyDate(); class MyDate { private int year, month, day; public void MyDate(int newYear, int newMonth, int newDay) { this.year = newYear; this.month = newMonth; this.day = newDay; } public void setDate(int newYear, int newMonth, int newDay) { this.year = newYear; this.month = newMonth; this.day = newDay; }... } Java does not create a default constructor if you have defined one

Constructors and UML You dont need to include constructors in the UML diagram

Constructor and Initialization Methods public void setPet(String newName, int newAge, double newWeight) { name = newName; if ((newAge < 0) || (newWeight < 0)) { System.out.println("Error: Negative age or weight."); System.exit(0); } else { age = newAge; weight = newWeight; }... public class Pet { private String name; private int age; //in years private double weight;//in pounds public Pet() { name = "No name yet."; age = 0; weight = 0; } public Pet(String initialName, int initialAge, double initialWeight) { name = initialName; if ((initialAge < 0) || (initialWeight < 0)) { System.out.println("Error: Negative age or weight."); System.exit(0); } else { age = initialAge; weight = initialWeight; }... The same code is frequently repeated

Calling Methods from Constructors public void setPet(String newName, int newAge, double newWeight) { name = newName; if ((newAge < 0) || (newWeight < 0)) { System.out.println("Error: Negative age or weight."); System.exit(0); } else { age = newAge; weight = newWeight; }... public class Pet { private String name; private int age; //in years private double weight;//in pounds public Pet() { name = "No name yet."; age = 0; weight = 0; } public Pet(String initialName, int initialAge, double initialWeight) { setPet(initialName, initialAge, initialWeight); }... Methods can be called from constructors You should avoid calling public methods

Prefer to Call a Private Method private void set(String newName, int newAge, double newWeight) { name = newName; if ((newAge < 0) || (newWeight < 0)) { System.out.println("Error: Negative age or weight."); System.exit(0); } else { age = newAge; weight = newWeight; } public void setPet(String newName, int newAge, double newWeight) { set(newName, newAge, newWeight); }... public class Pet { private String name; private int age; //in years private double weight;//in pounds public Pet() { name = "No name yet."; age = 0; weight = 0; } public Pet(String initialName, int initialAge, double initialWeight) { set(initialName, initialAge, initialWeight); }... public void setName(String newName) { set(newName, age, weight); } public void setAge(int newAge) { set(name, newAge, weight); }

Calling Constructors from Constructors private void set(String newName, int newAge, double newWeight) { name = newName; if ((newAge < 0) || (newWeight < 0)) { System.out.println("Error: Negative age or weight."); System.exit(0); } else { age = newAge; weight = newWeight; } public void setPet(String newName, int newAge, double newWeight) { set(newName, newAge, newWeight); }... public class Pet { private String name; private int age; //in years private double weight;//in pounds public Pet() { this(No Name yet., 0, 0); } public Pet(String initialName, int initialAge, double initialWeight) { set(initialName, initialAge, initialWeight); }... Must be the first statement in the constructor

Things to Remember About Constructors A constructor does not have any return type (not even void) You cannot call a constructor after creating an object If you define one constructor that is not the default one, Java will not define a default constructor for you So always include a default constructor You do not need to include constructors in UML diagrams You can call methods and other constructors from within a constructor In the case of methods prefer private methods In the case of constructors use this and make sure it is the first action in the constructor

The static Keyword Can be used both with variables and with methods Static variables and methods belong to a class and not an object They are disassociated from objects of a class

Static Variables Should be used with named constants public static final double FEET_PER_YARD = 3; Static variables are also called class variables Not to be confused with class types You can also have mutable static variables Do not use the final keyword One instance of the variable is allocated Can be used by non-static methods Java has three kinds of variables: local variables, instance variables, and static (class) variables.

Static Methods There are no instance variables this is no longer valid You should define methods that only use their parameters and constants as static Their implementation is is part of the class, but they do not operate on objects of the class public class DimensionConverter { public static final int INCHES_PER_FOOT = 12; public static double convertFeetToInches(double feet) { return feet * INCHES_PER_FOOT; } public static double convertInchesToFeet(double inches) { return inches / INCHES_PER_FOOT; } Utility class

Calling Non-static Methods from Static Is it possible? Generally no, but possible if you have a reference to an object Example: class Pet {... private void set(String newName, int newAge, double newWeight) { name = newName; if ((newAge < 0) || (newWeight < 0)) { System.out.println("Error: Negative age or weight."); System.exit(0); } else { age = newAge; weight = newWeight; }... public static void reset(Pet nullPet) { nullPet.set(Unknown name, 0, 0); }

About main() main is also a static method Same rules apply You can break down its functionality and distribute it to other static methods Code reuse, easier debugging, better readability

Compiler Concerns The compiler may not always understand what you want to do and complain Beware of null pointers if (something > somethingElse) return something; else if (something < somethingElse) return somethingElse; else return 0; int answer; if (something > somethingElse) answer = something; else if (something < somethingElse) answer = somethingElse; return answer; More complains here String test; if (test.equals(TEST)) { System.out.println(This is a test); } test does not reference an object. It is null

Privacy Leaks Instance variables should always be private For proper encapsulation To protect them from accidental overwrites To protect from bad guys However, using object references may completely override private When returning references to private instance variables When a method takes objects of its class as arguments Not really a security issue unless you are mixing code from different authors Can still lead to inconsistencies How to avoid them? Write separate accessor and mutator methods when needed, instead of returning a reference Use common sense

Enumerations Enumerations are classes Java defines a few default methods for enumeration classes equals(Suit) compareTo(Suit) ordinal(Suit) toString() valueOf(HEARTS); The visibility enumeration classes is by default private enum Suit {CLUBS, DIAMONDS, HEARTS, SPADES}; Suit s = Suit.DIAMONS Same as named constants. public static final …