Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS-0401 INTERMEDIATE PROGRAMMING USING JAVA

Similar presentations


Presentation on theme: "CS-0401 INTERMEDIATE PROGRAMMING USING JAVA"— Presentation transcript:

1 CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Spring 2018

2 Chapter 8 A Second Look at Classes and Objects

3 Chapter 8 Outline Static Class Members
Passing Objects as Arguments to Methods Returning Objects from Methods The toString Method Writing an equals Method Methods that Copy Objects Aggregation The this Reference Variable Enumerated Types

4 Static Class Members

5 Static Class Members Owner: John Price Tag: $2000.00 Model: Xtreme
Color: Light blue Owner: Daniel Price Tag: $ Model: ProBike Color: Black Each Bike Fields (owner, price, model, and color) has a unique value for a given bike object, e.g., different colors, different prices, etc. We need to create a bike object for each bike and each bike will have its own set of field values

6 Earth Class Fields Size Mass Surface Temperature

7 Would this make any sense?
Static Fields Would this make any sense? Earth myEarth = new Earth(); Earth yourEarth = new Earth(); System.out.println(“My Earth size is “ + myEarth.size); System.out.println(“Your Earth size is “ + yourEarth.size);

8 Static Fields Main Points:
Earth is unique. There is no such thing like “My Earth” or “Your Earth” Its field values would be the same for each single object (differently of the Bike example) We should not need to create Earth objects to access the Earth fields (mass, size, surface temperature) The Earth fields would be the same for all objects created from the Earth Class They are static fields!!!!

9 Example of Static Fields
The number PI (p) is always , it does not matter who is using it. This number is defined in the Math Class as public static final double PI = ; We use PI by calling the Class Name! No need to create an object of it Math myMath = new Math(); // Error during compilation double area = myMath.PI * r * r; // Can’t be done double area = Math.PI *r * r;

10 Java API Math Documentation

11 Static Methods Remember what we have learned on how to call a class method until now: ClassName objectName = new ClassName(); objectName.classMethod(); Example: House myHouse = new House(); myHouse.getNumberOfBedrooms(); However some methods are not “object” dependent, i.e., they do not need to be called from an object to perform its intended task

12 Math Methods are Static

13 Static Methods We do not need to create an instance of a math class to use the sqrt() method sqrt(9) will always give the same value of 3, it does not matter what object has called it Same thing for a cosine(45), or any other math calculation double value = Math.sqrt(9); double diff = Math.abs(-15); double tangent = Math.tan(x);

14 Time out double y = Math.abs(x);
Which of those 4 abs() methods will JVM call? How do we call when we have methods with the same name but different input arguments?

15 Passing Objects as Arguments and getting objects to and from methods

16 The Main Elements of a Method (*)
<pt> <mod> <rt> <mn> (list of <at an>) { java statements; return ro; } Where: pt = permission type: private, public, protected mod = static, final, or nothing rt = object returned type (int, double, car) mn = method name (remember camelCase) at = argument type (int, double, car, or empty) an = argument name (remember camelCase) ro = returned object or variable value (or nothing) (*) commands in yellow means mandatory entry - All Rights Reserved

17 Calling Methods Within your Class
// method defined inside your class public double area( double radius) { double ans = Math.PI * radius * radius; return ans; } public int main() { double rad = 2.0; double theArea = area(rad); Note #1: If method is called in same class in which it was defined, we don’t need to use the class name in the call Note #2: parameter name does not need to have the same name as the argument name. They only must have the same type (double) parameter argument - All Rights Reserved

18 Same thing for Objects Class Circle { public double radius; public String color; public Point2D coordinatesXY; // the constructors are not shown here, but they exist } /// in another file in the netbeans project… Circle myCircle = new Circle(4.0, “Blue”, xyCoordHere); double myArea = computeArea(myCycle); // method defined inside your class public double computeArea(Circle circ) { double ans = Math.PI * circ.radius * circ.radius; return ans; public Circle createCircle(double r, String c, Point2D loc) { Circle tempCircle = new Circle(); tempCircle.radius = r; tempCircle.color = c; tempCircle.coordinatesXY = loc; return tempCircle; Circle newCircle = createCircle(4.0, “Blue”, loc);

19 The toString() Method

20 The Mother of all classes
All classes inherit some methods from the Object class Class inheritance will be discussed later on this semester Two important methods that any class inherits from the Object class (including the ones that you develop) are: toString() equals() You do not need to create them! Java knows that they have been inherited by your class from the Object class

21 toString() in Action… Discuss BikeStore application Important points:
Using the object’s name in System.out.println will invoke toString() method in the Bike class If the toString() method is not overridden in the Bike class, then the toString() method from the Object class will be used The toString() method from the Object class returns a string of the class name and its location in memory We can override this method inside our class (Bike) to print some more useful information (such as the bike type)

22 The equals() Method

23 public class Vehicle { private String model; private int yearOfProduction; private String manufacturer; } Vehicle myCar = new Vehicle("Focus",2002,"Ford"); Vehicle yourCar = new Vehicle("Focus",2002,"Ford"); if (myCar == yourCar) { System.out.println("We have the same type of car"); }

24 yourName.equals(myName)
The equals() method We know that the regular operator == will not work for us when comparing two objects contents That’s why when comparing two Strings we use yourName.equals(myName) Notes: using “==“ makes Java to call an Object method called equals(). equals() standard behavior is to compare the objects memory location But we want to compare two objects by checking if their fields have the same values instead of comparing objects memory location. So how do we do it?

25 The equals() method The standard practice in Java development is to override the equals() method inside your class Have your equals() method to compare all the fields that matters for you

26 The equals() method public class Vehicle { private String model;
private int yearOfProduction; private String manufacturer; public Vehicle(String model, int yearOfProduction, String manufacturer) { this.model = model; this.yearOfProduction = yearOfProduction; this.manufacturer = manufacturer; } public boolean equals(Vehicle v) { if ( (v == null) && !(v instanceof Vehicle) ) return false; return ( (this.model).equals(v.model) && (this.yearOfProduction == v.yearOfProduction) && (this.manufacturer).equals(v.manufacturer) );

27 The equals() method public class Main {
public static void main(String[] args) { Vehicle myCar = new Vehicle("Focus",2002,"Ford"); Vehicle minivan = new Vehicle ("Odyssey",2014,"Honda"); Vehicle focus = new Vehicle("Focus",2002,"Ford"); if (myCar.equals(minivan)) { System.out.println("This isn't supposed to print!"); } if (myCar.equals(focus)) { System.out.println("The equals method is implemented OK");

28 Methods that Copy Objects

29 Methods that Copy Objects
public class Vehicle { private String model; private int yearOfProduction; private String manufacturer; } Vehicle myCar = new Vehicle("Focus",2002,"Ford"); Vehicle yourCar = myCar; if (myCar == yourCar) { System.out.println("We have the same type of car"); }

30 Methods that Copy Objects
Copying by reference can be a security risk! You give a “believe to be” copy of an object to someone, and this someone can change your original object too!

31 Methods that Copy Objects
There are many ways of copying (or cloning) an object Textbook shows two of them: Creating an ordinary method to copy an element Creating a class copy constructor

32 Creating an ordinary method to copy an element

33 Creating an ordinary method to copy an element
public class Vehicle { private String model; private int yearOfProduction; private String manufacturer; public Vehicle(String model, int yearOfProduction, String manufacturer) { this.model = model; this.yearOfProduction = yearOfProduction; this.manufacturer = manufacturer; } public Vehicle copy() { Vehicle copyVehicle = new Vehicle(model, yearOfProduction, manufacturer); return copyVehicle; //////////////////////////////////// Vehicle yourVehicle = new Vehicle(“Montero”, 2003, “Mitsubishi”); Vehicle myVehicle = yourVehicle.copy(); boolean isSameCar = (yourVehicle == myVehicle);

34 Creating a class copy constructor

35 Creating a class copy constructor
public class Vehicle { private String model; private int yearOfProduction; private String manufacturer; public Vehicle(String model, int yearOfProduction, String manufacturer) { this.model = model; this.yearOfProduction = yearOfProduction; this.manufacturer = manufacturer; } public Vehicle(Vehicle v) { model = v.model; yearOfProduction = v.yearOfProduction; manufacturer = v.manufacturer; //////////////////////////////////// Vehicle yourVehicle = new Vehicle(“Montero”, 2003, “Mitsubishi”); Vehicle myVehicle = new Vehicle(yourVehicle); boolean isSameCar = (yourVehicle == myVehicle);

36 Aggregation

37 Aggregation double price; String model; String manufacturer;
boolean singleOwner; // all fields above are of primitive types double price; String model; String manufacturer; // Fields are objects of other classes Engine engineType; Tire tireType; Seat seatType;

38 Aggregation A Car Class can define fields of the type:
Primitive (price, color, mileage, etc.) Objects (tire, engine, seat, etc.) The process of a class having objects of other classes as fields is known as Aggregation

39 Aggregation Example Prof. Dr. Paulo Brasko Ferreira Spring 2018
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Spring 2018

40 Wrong way of creating a Class Course
// course general description String title; int roomNumber; String meetingDays; double startTime; // instructor info String instructorFirstName; String instructorLastName; String highestDegree; // textbook info String textbookName; int editionNumber; String author; double isbn; }

41 One good way… class Instructor { class Textbook { // instructor info
String instructorFirstName; String instructorLastName; String highestDegree; } class Textbook { // textbook info String textbookName; int editionNumber; String author; double isbn; } class Course { // course general description String title; int roomNumber; String meetingDays; double startTime; Instructor instructor; Textbook book; }

42 Sample Code Chapter 08 Source Code from my website Instructor.java
Textbook.java Course.java CourseDemo.java

43 Advantages of using Aggregation
Work on one class at a time helps development of very complex programs Easier to work as a team: each team member can be responsible for one part, and his/her development does not impact in the other parts of the main application Easier to test: each task can be separately tested before adding it in the main application Easier to debug Easier to extend functionality without the need to retest the all the other classes that have not been touched

44 Be Careful With Few Things
Be sure to check if an object is not null before trying to perform an operation on it If the instructor has not been defined yet and you try to get her/his first name, the code will abort use IF statement such as if(teacher != null) In the default constructor, set name to “ “ Avoid passing the reference of an object. The external program could change a value of the object that should not be changed Pass a copy of the object

45 Examples public Instructor getInstructor(){
// security issue here! return instructor; } public Instructor getInstructor() { // Return a copy of the instructor object. return new Instructor(instructor); } public Instructor() { // avoiding null later on firstName = “ “; lastName = “ “; } public String getFullName() { if( (lastName != null) && (firstName != null) { return firstName + lastName; }

46 The this Reference

47 public class SportsCar {
private CarType make; // The car's make private CarColor color; // The car's color private double price; // The car's price /** * The constructor initializes the car's make, color, and price. * aMake The car's make. aColor The car's color. aPrice The car's price. */ public SportsCar(CarType aMake, CarColor aColor, double aPrice) { make = aMake; color = aColor; price = aPrice; }

48 public class SportsCar {
private CarType make; // The car's make private CarColor color; // The car's color private double price; // The car's price /** * The constructor initializes the car's make, color, and price. * make The car's make. color The car's color. price The car's price. */ public SportsCar(CarType make, CarColor color, double price) { this.make = make; this.color = color; this.price = price; }

49 Green color, representing a class field
Black color, representing a local variable

50 Enumerated Types

51 Are you sure that you will remember their meaning one year from now???
Enumerated Types public double getCarPrice(int carType) { if ( carType == 1) { return 10000; } else if (carType == 2) { return 15000; } else if (carType == 3) { return 20000; } Are you sure that you will remember their meaning one year from now??? Sure you know what kind of cars the numbers 1, 2, and 3 represent; you just did the code yesterday! And if you retire or leave the company, will the next programmer know what they mean?

52 int Corolla = 1; int Camry = 2; int Rav4 = 3; public double getCarPrice(int carType) { if ( carType == Corolla) { return 10000; } else if (carType == Camry) { return 15000; } else if (carType == Rav4) { return 20000; } enum CarType { Corolla, Camry, Rav4 } public double getCarPrice(CarType carType) { if ( carType == CarType.Corolla) { return 10000; } else if (carType == CarType.Camry) { return 15000; } else if (carType == CarType.Rav4) { return 20000; }

53 It can be used for setters too
public void setColor (String newColor) { if (newColor.equals(“Red) || newColor.equals(“Blue”) || newColor.equals(“Black”) { this.color = newColor; } else { System.out.println(“Invalid Color”); } enum CarColor { Red, Black, Blue, Silver } public void setColor(CarColor newColor) { this.color = newColor; }

54 Enumeration Examples SportsCar.java CarColor.java CarType.java SportsCarDemo.java SportsCarDemos2.java (switch/enum example)


Download ppt "CS-0401 INTERMEDIATE PROGRAMMING USING JAVA"

Similar presentations


Ads by Google