27
Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS [email protected]

Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS [email protected]

Embed Size (px)

Citation preview

Page 1: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

Intro to CS – Honors IMore Objects and MethodsGEORGIOS PORTOKALIDIS

[email protected]

Page 2: 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, …)

The method name, number of parameters, and their type constitutes a method’s signature

MethodName(Type Parameter, Type Parameter, …)

A primitive or class type, or void

0 or more paremeters

A method’s heading

A method’s signature

Page 3: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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

Page 4: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

Overloading Methods Java allows you to define multiple methods with the same name and different signaturesclass 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

Page 5: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

Overloading Methods Java allows you to define multiple methods with the same name and different signaturesclass 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

Page 6: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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

Page 7: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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

Page 8: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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

Page 9: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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

Page 10: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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

- 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 object’s instance variables with default values

Page 11: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

Example of Constructorspublic class Pet{

private String name;private int age; //in yearsprivate 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

Page 12: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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

Page 13: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

Constructors and UML

You don’t need to include constructors in the UML diagram

Page 14: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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 yearsprivate 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

Page 15: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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 yearsprivate 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

Page 16: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

Prefer to Call a Private Methodprivate 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 yearsprivate 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);}

Page 17: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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 yearsprivate 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

Page 18: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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

Page 19: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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

Page 20: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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.

Page 21: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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

Page 22: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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

}

Page 23: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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

Page 24: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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

Page 25: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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

Page 26: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU

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 …

Page 27: Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS GPORTOKA@STEVENS.EDU