270 likes | 380 Views
Intro to CS – Honors I More Objects and Methods. Georgios Portokalidis gportoka@stevens.edu. A Method’s Heading. Defining a method requires the following ReturnType MethodName ( Type Parameter, Type Parameter, …)
E N D
Intro to CS – Honors IMore Objects and Methods Georgios Portokalidis gportoka@stevens.edu
A Method’s Heading • Defining a method requires the following • ReturnTypeMethodName(Type Parameter, Type Parameter, …) • The method name, number of parameters, and their type constitutes a method’s signature • MethodName(Type Parameter, Type Parameter, …) A method’s heading A primitive or class type, or void 0 or more paremeters A method’s 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(intnewYear, intnewMonth, intnewDay) { this.year = newYear; this.month = newMonth; this.day = newDay; } public void setDate(intnewYear, intnewMonth) { this.year = newYear; this.month = newMonth; this.day = -1; // So we know it was not set } public void setDate(intnewYear) { 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(StringsubString) { string += subString; } public void append(float floatNumber) { string += floatNumber; } public void append(doubledoubleNumber) { 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(StringsubString) { string += subString; } public void append(float floatNumber) { string += floatNumber; } public void append(doubledoubleNumber) { string += doubleNumber; } } Same method name, same number of arguments, different types
Overloading and Automatic Type Casting class MyString { private String string; public void append(int integer) { string += integer; } public void append(StringsubString) { string += subString; } public void append(float floatNumber) { string += floatNumber; } public void append(doubledoubleNumber) { string += doubleNumber; } } • Java automatically casts types when they fit • byte → short → int → long → float → double • MyStringstr = new MyString(); • byte data = 10; • str.append(data); • Which method will be picked?
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() . . . These routines cannot be declared in the same class You cannot overload based on the return type
Things to Remember About Overloading • A method’s 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 object’s 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 Species - name: String - population: int - growthRate: double + setSpecies(String newName, intnewPopulation, double newGrowthRate): void + getName(): String + getPopulation(): int + getGrowthRate( ): growthRate + writeOutput(): void If none were defined, Java will create a default constructor that initializes the object’s 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, intinitialAge, 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(intnewYear, intnewMonth, intnewDay) { this.year = newYear; this.month = newMonth; this.day = newDay; } public void setDate(intnewYear, intnewMonth, intnewDay) { 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 don’t need to include constructors in the UML diagram
Constructor and Initialization Methods • 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, intinitialAge, 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; • } • } • ... • public void setPet(String newName, intnewAge, 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; • } • } • ... The same code is frequently repeated
Calling Methods from 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, intinitialAge, double initialWeight) • { • setPet(initialName, initialAge, initialWeight); • } • ... • public void setPet(String newName, intnewAge, 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; • } • } • ... Methods can be called from constructors You should avoid calling public methods
Prefer to Call a Private Method • 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, intinitialAge, double initialWeight) • { • set(initialName, initialAge, initialWeight); • } • ... • private void set(String newName, intnewAge, 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, intnewAge, double newWeight) • { • set(newName, newAge, newWeight); • } • ... • public void setName(String newName) • { • set(newName, age, weight); • } • public void setAge(intnewAge) • { • set(name, newAge, weight); • }
Calling Constructors from Constructors • 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, intinitialAge, double initialWeight) • { • set(initialName, initialAge, initialWeight); • } • ... • private void set(String newName, intnewAge, 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, intnewAge, double newWeight) • { • set(newName, newAge, newWeight); • } • ... 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 Utility 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; • } • }
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, intnewAge, 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 otherstatic 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; test does not reference an object. It is null More complains here String test; if (test.equals(“TEST”)) { System.out.println(“This is a test”); } int answer; if (something > somethingElse) answer = something; else if (something < somethingElse) answer = somethingElse; return answer;
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 Same as named constants. public static final … • 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