Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS"— Presentation transcript:

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

2 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

3 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

4 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

5 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

6 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; }

7 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

8 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

9 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

10 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

11 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

12 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

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

14 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

15 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

16 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); }

17 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

18 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

19 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

20 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.

21 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

22 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); }

23 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

24 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

25 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

26 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 …

27


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

Similar presentations


Ads by Google