Presentation is loading. Please wait.

Presentation is loading. Please wait.

More About Objects and Methods CS140: Introduction to Computing 1 Savitch Chapter 6 10/16/13.

Similar presentations


Presentation on theme: "More About Objects and Methods CS140: Introduction to Computing 1 Savitch Chapter 6 10/16/13."— Presentation transcript:

1 More About Objects and Methods CS140: Introduction to Computing 1 Savitch Chapter 6 10/16/13

2 Constructors Person p_1 = new Person(); 2 constructor

3 The Constructor Method When you create an object of a class with new, you invoke the constructor method Constructors are only called when you create an object The constructor method creates and initializes a new object whose address is then given back to the object 3

4 The Constructor Method Constructors have no return type/value or a return statement Constructors really return the address to the newly created object Constructors are only called when you create an object, so if you want to change the state of the object, use a set method 4

5 The Constructor Method Constructor(s) MUST have the same name of as the class When a constructor is called, Java assigns default values to all instance variables You can create your own constructor(s) If you don’t create a constructor, Java auto creates and invokes a default constructor for you If you create even one custom constructor, Java won’t do it for you anymore 5

6 The Constructor Method public Person() {…} You should always implement the standard constructor, regardless of whether or not you plan to use it 6 the standard constructor, no formal parameters

7 The Constructor Method 7 public Person() { this.name = ""; this.role = ""; this.major = ""; this.gender = ' '; this.age = 0; } public Person( String name ) { this.name = name; this.role = ""; this.major = ""; this.gender = ' '; this.age = 0; } public Person( String name, int age ) { this.name = name; this.role = ""; this.major = ""; this.gender = ' '; this.age = age; } public Person( String name, String role, String major, char gender, int age ) { this.name = name; this.role = role; this.major = major; this.gender = gender; this.age = age; }

8 The Constructor Method Convention: Constructor declarations are grouped before all other methods in the class Class diagrams – constructors are normally omitted Like any other method, constructors can call other methods Bad idea to call public methods, because other classes can alter these methods and change the behavior of the constructor. If you call other methods from the constructor, they should be private 8

9 The Constructor Method Constructors can call other constructors However, if you call another constructor, this MUST be the first action taken by the constructor 9 public Person() { this.name = ""; this.role = ""; this.major = ""; this.gender = ' '; this.age = 0; } public Person( String name ) { this(); this.name = name; }

10 The Constructor Method 10 public Person() { this.name = ""; this.role = ""; this.major = ""; this.gender = ' '; this.age = 0; } public Person( String name ) { this(); this.name = name; } public Person( String name, int age ) { this(name, "", "", ' ', age); } public Person( String name, String role, String major, char gender, int age ) { this.name = name; this.role = role; this.major = major; this.gender = gender; this.age = age; }

11 Variables Java has three types of variables – local – instance – static 11

12 static Variables Variables and methods can be declared static public static final double FEET_PER_YARD = 3; Only one single copy exists Every instance of the containing class shares and uses that one copy 12

13 static Variables static variables (or methods) belong to the class as a whole and NOT to a particular object static variables can be initialized static variables can also be private, and if they are NOT constants ( public static final ), they SHOULD be private 13

14 static Variables public class Person{ public String name; public String role; public String major; public char gender; private int age; private static int numberOfPeople = 0; public Person() { this.name = ""; this.role = ""; this.major = ""; this.gender = ' '; this.age = 0; numberOfPeople++; } public int getClassSize() { return numberOfPeople; } 14 public static void main (String[] args) { Person p_1 = new Person(); Person p_2 = new Person(); Person p_3 = new Person(); System.out.println(p_1.getClassSize()); System.out.println(p_3.getClassSize()); } 333333 333333

15 static Methods static Methods are methods that don’t relate to objects – e.g. compute the average of two numbers, unit conversions etc. static Methods are invoked without using any object, they are invoked by using the class name static Methods CANNOT refer to instance variables, as they don’t relate to any object 15

16 static Variables public class Person{ public String name; public String role; public String major; public char gender; private int age; private static int numberOfPeople = 0; public Person() { this.name = ""; this.role = ""; this.major = ""; this.gender = ' '; this.age = 0; numberOfPeople++; } public static int getClassSize() { return numberOfPeople; } 16 public static void main (String[] args) { Person p_1 = new Person(); Person p_2 = new Person(); Person p_3 = new Person(); System.out.println(Person.getClassSize()); } 3 3

17 static Methods It may be convenient to implement a class of static methods to use for your programs static Methods CANNOT call a non-static method without an object, so if you need a non-static method call in a static method, you have to pass it an object as an argument 17

18 static Variables public class Person{ public String name; public String role; public String major; public char gender; private int age; private static int numberOfPeople = 0; public Person() { this.name = ""; this.role = ""; this.major = ""; this.gender = ' '; this.age = 0; numberOfPeople++; } public static int getClassSize( Person aPersonObj ) { System.out.print( "Object’s age: " ); System.out.println( aPersonObj.getAge() ); System.out.print( “Class size: " ); return numberOfPeople; } public int setAge( int age ) { this.age = age; } public int getAge() { return age; } 18 public static void main (String[] args) { Person p_1 = new Person(); p_1.setAge(100); Person p_2 = new Person(); Person p_3 = new Person(); System.out.println(Person.getClassSize(p_1)); } Object’s age: 100 Class size: 3 Object’s age: 100 Class size: 3

19 main is static The main method is static You can add a main method to every class for testing purposes When the class is run as a program, the main method executes If the class is only referenced by another program, the main method is ignored 19

20 The Math Class A set of standard mathematical methods No need for to import All its methods are static, so you don’t need an object to call them, you use the class name 20

21 The Math Class 21 for argument and return types look at table on page 402 Math.pow(2.0, 3.0) Math.abs(-7.8) Math.max(5, 42) Math.min(5, 42) Math.random() Math.round(5.4) Math.round(5.5) Math.ceil(5.4) Math.ceil(5.9) Math.floor(5.4) Math.floor(5.9) Math.sqrt(16.0) 8.0 7.8 42 5 0.384933008844055 5 6 6.0 5.0 4.0

22 Wrapper Classes Sometimes we need to convert a primitive type value to an “equivalent” value of some class type  use wrapper classes Wrapper classes provide methods that can act on values of primitive type Every primitive type has a wrapper class Wrapper classes have NO default constructor 22

23 Wrapper Classes - boxing int  Integer double  Double char  Character int i = 6; Integer o_i = new Integer(i); String o_iS = o_i.toString() + "is a string"; can be written in short form Integer o_i = 6; Double o_d = 9.99; 23

24 Wrapper Classes - unboxing Integer  int Double  double Character  char Integer o_i = 6; int j = o_i.intValue(); can be written in short form int j = o_i; int j = new Integer(6); 24

25 Wrapper Classes Integer.MAX_VALUE  2147483647 Integer.MIN_VALUE  -2147483648 Integer.TYPE  int Integer.SIZE  32 Character.SIZE  16 Convert Strings to int, double, long, or float double d = Double.parseDouble( "199.99" ); String s = "199.56"; d = Double.parseDouble( s ); d = Double.parseDouble( s.trim() ); 25 Double.MAX_VALUE  1.7976931348623157E308 Double.MIN_VALUE  4.9E-324 Double.TYPE  double Double.SIZE  64 String t = "1678"; int i = Integer.parseInt( t ); for useful class Character methods look at table on page 407 Useful!!!

26 So far… Chapters 6.1 and 6.2 26

27 What is displayed? 1.0 2.60 3.Nothing 4.IDK 27 11111111 public class MyTime { private int hour; private int min; public static final int MIN_IN_HOUR = 60; } public static void main(String[] args) { MyTime myTime = new MyTime(); System.out.print(MyTime.hour); }

28 What is displayed? 1.0 2.60 3.Nothing 4.IDK 28 11111111 public class MyTime { private int hour; private int min; public static final int MIN_IN_HOUR = 60; } public static void main(String[] args) { MyTime myTime = new MyTime(); System.out.print(MyTime. MIN_IN_HOUR ); }

29 What should the return type be? 1.void 2.int 3.float 4.none of these 29 11111111 public class MyTime { private int hour; private int min; public MyTime(){ hour = 0; min = 0; } //compare two MyTime objects public _______equals(){ //TODO comparison logic }

30 What is should the parameter type be? 1.void 2.int 3.MyTime 4.none of these 30 11111111 public class MyTime { private int hour; private int min; public MyTime(){ hour = 0; min = 0; } //compare two MyTime objects public boolean equals(___ obj){ //TODO comparison logic }

31 What is missing? 1.this. 2.foo. 3.MyTime. 4.none of these 31 11111111 public class MyTime { private int hour; private int min; public MyTime(){ hour = 0; min = 0; } public boolean equals(MyTime foo){ if( ___ min == min && ___ hour == hour) return true; else return false; }

32 public class Ball { private int x, y; private int velocityY; private int velocityX; private static final int RADIUS = 10; private static final int GRAVITY = 3; public Ball() { x = 0; y = 0; velocityY = 0; velocityX = 0; } 32

33 How many copies of bc? 1.1 2.2 3.one per object 4.0 33 11111111 public class Ball { private int x, y; private int velocityY; private int velocityX; private static final int RADIUS = 10; private static final int GRAVITY = 3; private static int bc = 0; public Ball() { x = 0; y = 0; velocityY = 0; velocityX = 0; }

34 public class Ball { private int x, y; private int velocityY; private int velocityX; private static final int RADIUS = 10; private static final int GRAVITY = 3; public static int ballCount = 0; public Ball() { x = 0; y = 0; velocityY = 0; velocityX = 0; ballCount++; } 34

35 How many copies of totalDeposits? 1.1 2.2 3.one per object 4.0 35 11111111 public class BankAcct{ int acctNum; double balance; private static double interest = 1.9; private static double totalDeposits = 0; BankAcct(int number) { acctNum = number; balance = 0.0; }

36 How to update totalDeposits? 1.totalDeposits += deposit 2.this.totalDeposits += deposit 3.BankAcct.totalDeposits += deposit 4.IDK 36 11111111 public class BankAcct{ int acctNum; double balance; private static double interest = 1.9; //sum of account balances private static double totalDeposits = 0; BankAcct(int number) { acctNum = number; balance = 0.0; } public void deposit(double deposit){ balance += deposit; ____________________; }

37 public class BankAcct{ int acctNum; double balance; private static double interest = 1.9; //sum of account balances private static double totalDeposits = 0; BankAcct(int number) { acctNum = number; balance = 0.0; } public void deposit(double deposit){ balance += deposit; totalDeposits += deposit; } 37

38 Two add() methods ? 1.Error 2.OK if the parameter types differ 3.OK if the parameter names differ 4.IDK 38 11111111 class MyTime { private int hour; private int min; MyTime(){ hour = 0; min = 0; } public void add(int min){ this.min += min; } public void add(int hour){ this.hour += hour; }

39 Two add() methods ? 1.Error 2.OK if param. type and/or number of param. differ 3.OK if the parameter names differ 4.IDK 39 11111111 class MyTime { private int hour; private int min; MyTime(){ hour = 0; min = 0; } public void add(int m, int h){ min += m; hour += h; } public void add(int hour){ this.hour += hour; }

40 Two add() methods ? 1.Error 2.OK if the return types differ 3.OK if the parameter names differ 4.OK if param. type and/or number of param. differ 40 11111111 class MyTime { private int hour; private int min; MyTime(){ hour = 0; min = 0; } public void add(int min){ this.min += min; } public int add(int min){ this.min += min; return this.min; } }

41 Overloading Methods that belong to the same class can have the same name (overloading the method name), however, parameter lists MUST differ (in number and/or type) so when you invoke the method, Java knows which one you mean You cannot define two or more methods with the same name and parameter number and type in the same class You cannot overload based on return type Avoid overloading if possible 41

42 Overloading 42

43 Overloading - constructors 43 public Person() { this.name = ""; this.role = ""; this.major = ""; this.gender = ' '; this.age = 0; } public Person( String name ) { this(); this.name = name; } public Person( String name, int age ) { this(name, "", "", ' ', age); } public Person( String name, String role, String major, char gender, int age ) { this.name = name; this.role = role; this.major = major; this.gender = gender; this.age = age; } Person p_1 = new Person(); Person p_2 = new Person( " Olaf " ); Person p_3 = new Person( " Olaf ", 50 ); Person p_4 = new Person( " Olaf ", " student ", " CS ", 'F', 50 );

44 So far 6.1, 6.2, 6.3, 6.4 Skip 6.5 Go to 6.6 and 6.7 44

45 Enumeration 45

46 46 enum MovieRating {G, PG, PG13, NC17, R} public static void main(String[] args) { MovieRating rating; rating = MovieRating.PG13; switch(rating) { case G: System.out.println(“G: General Audiences”); break; case PG: System.out.println(“PG: Parental Guidance Suggested”); break; case PG13: System.out.println(“PG13: Parents Strongly Cautioned”); break; case NC17: System.out.println(“NC17: No One 17 and Under Admitted”); break; case R: System.out.println(“R: Restricted”); break; default: System.out.println(“Not a valid rating”); } declare valid values declare variable and assign value check the value of the variable rating

47 Enhanced enumerator (p. 440) enum Suit { CLUBS("black"), DIAMONDS("red"), HEARTS("red"), SPADES("black"); private final String color; private Suit(String sColor) { color = sColor; } public String getColor() { return color; } } 47

48 enum Suit { CLUBS("black"), DIAMONDS("red"), HEARTS("red"), SPADES("black"); private final String color; private Suit(String sColor) { color = sColor; } public String getColor() { return color; } } 48 When the compiler encounters the enumerator, it creates a class Suit

49 public class Test2 { enum Suit { CLUBS("black"), DIAMONDS("red"), HEARTS("red"), SPADES("black"); private final String color; private Suit(String sColor) { color = sColor; } public String getColor() { return color; } public static void main(String[] args){ Suit s_1 = Suit.DIAMONDS; s_1.compareTo(Suit.HEARTS); s_1.equals(Suit.HEARTS); s_1.getClass(); s_1.getColor(); s_1.ordinal(); Suit.CLUBS.ordinal() s_1.toString(); Suit.valueOf("SPADES"); } 49 -1 (returns negative, 0 or positive number) false class test2.Test2$Suit red 1 0 "DIAMONDS" returns object Suit.HEARTS defining instance variables lets you assign values to the objects in the enumeration a get method lets you access the instance variables if you omit the access modifier, enumerator is implicitly defined as private private so you cannot invoke it directly, it’s called only within the definition of Suit

50 private final String color ? 1.Member of Suit objects 2.Method of Suit objects 3.Constructor of Suit objects 4.IDK 50 11111111 enum Suit { CLUBS("black"), DIAMONDS("red"), HEARTS("red"), SPADES("black"); private final String color; private Suit(String sColor) { color = sColor; } public String getColor() { return color; } }

51 private Suit(String sColor) ? 1.Member of Suit objects 2.Method of Suit objects 3.Constructor of Suit objects 4.( ╯ °□°) ╯︵ ┻━┻ 51 11111111 enum Suit { CLUBS("black"), DIAMONDS("red"), HEARTS("red"), SPADES("black"); private final String color; private Suit(String sColor) { color = sColor; } public String getColor() { return color; } }

52 Packages A named collection of related classes A package is a collection of classes, each in a separate file, placed in the same folder; name of the package is the same as the name of the folder package package_name; class class_name { } 52 first non-comment statement in a file to use elsewhere: import package_name.class_name; import package_name.*; to use elsewhere: import package_name.class_name; import package_name.*;

53 Packages package package_name; 53 the directory name containing the package classes relative to the Java base directory base directory package name: general.utilities import general.utilities.Person;

54 NetBeans specific: The name of package is under the src folder 54 package enumdemo

55 Name clashes mystuff.CoolClass object1 = new mystuff.CoolClass(); yourstuff.CoolClass object2 = new yourstuff.CoolClass(); 55

56 So far If you haven’t read Chapter 6 yet, read it Next – Arrays - Chapter 7 56


Download ppt "More About Objects and Methods CS140: Introduction to Computing 1 Savitch Chapter 6 10/16/13."

Similar presentations


Ads by Google