Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.

Slides:



Advertisements
Similar presentations
Basic -2 Classes and Objects. Classes and Objects A class is a complex data TYPE An object is an instance of a class. Example: Class: Person Objects:
Advertisements

Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
9-1 Chapter.8 Classes & Objects: A deeper look –Static Class Members –Passing & Returning Objects from Methods –The toString method –Writing an equals.
Chapter 8: A Second Look at Classes and Objects
© 2010 Pearson Addison-Wesley. All rights reserved. 9-1 Chapter Topics Chapter 9 discusses the following main topics: –Static Class Members –Passing Objects.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
1 More on Classes Overview l Overloading l The this keyword l The toString method l The equals method.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
BPJ444: Business Programming Using Java Classes and Objects Tim McKenna
Class and Object. Class vs Object Let us consider the following scenario… Class defines a set of attributes/fields and a set of methods/services. Object.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Java Classes Appendix C © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
9-2  Static Class Members  Passing Objects as Arguments to Methods  Returning Objects from Methods  The toString method  Writing an equals Method.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes: Cooper & Ji & Varol Fall 09.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 9: A Second Look at Classes and Objects
CSE 501N Fall ‘09 04: Introduction to Objects 08 September 2009 Nick Leidenfrost.
Objects and Classes Mostafa Abdallah
Chapter 9 – Part Tony Gaddis Modified by Elizabeth Adams.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
A note about coverage Say you have an if statement:
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Introduction To Objects Oriented Programming Instructor: Mohammed Faisal.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Topics Instance variables, set and get methods Encapsulation
Java Classes Introduction. Contents Introduction Objects and Classes Using the Methods in a Java Class – References and Aliases Defining a Java Class.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Class Everything in Java is in a class. The class has a constructor that creates the object. If you do not supply a constructor Java will create a default.
Starting Out With Java Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 9 Slide #1 Review.
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Introduction to Constructors Lecture # 4. Copyright © 2011 Pearson Education, Inc. 3-2 Arguments Passed By Value In Java, all arguments to a method are.
Java: Base Types All information has a type or class designation
Chapter 9 A Second Look at Classes and Objects - 2.
A Second Look at Classes and Objects - 1 Static Class Members
Static data members Constructors and Destructors
Java: Base Types All information has a type or class designation
Java Primer 1: Types, Classes and Operators
Topics Static Class Members Overloaded Methods Overloaded Constructors
Chapter 3: Using Methods, Classes, and Objects
A Second Look at Classes and Objects - 2
Chapter 9: A Second Look at Classes and Objects
Chapter 9: A Second Look at Classes and Objects
Introduction to Classes
Classes & Objects: Examples
Today’s topics UML Diagramming review of terms
Assessment – Java Basics: Part 1
Object Oriented Programming Review
Handout-4b More on Classes
Dr. Sampath Jayarathna Cal Poly Pomona
String Class.
Presentation transcript:

Lecture # 8 Constructors Overloading

Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors – Passing Objects as Arguments to Methods – Returning Objects from Methods – The toString method – Writing an equals method

Review of Instance Fields and Methods Each instance of a class has its own copy of instance variables. – Example: The Rectangle class defines a length and a width field. Each instance of the Rectangle class can have different values stored in its length and width fields. Instance methods require that an instance of a class be created in order to be used. Instance methods typically interact with instance fields or calculate values based on those fields.

Static Class Members Static fields and static methods do not belong to a single instance of a class. To invoke a static method or use a static field, the class name, rather than the instance name, is used. Example: double val = Math.sqrt(25.0); Class nameStatic method

Static Fields Class fields are declared using the static keyword between the access specifier and the field type. private static int instanceCount = 0; The field is initialized to 0 only once, regardless of the number of times the class is instantiated. – Primitive static fields are initialized to 0 if no initialization is performed.

Static Fields instanceCount field (static) 3 Object1Object3Object2

Static Methods Methods can also be declared static by placing the static keyword between the access modifier and the return type of the method. public static double milesToKilometers(double miles) {…} When a class contains a static method, it is not necessary to create an instance of the class in order to use the method. double kilosPerMile = Metric.milesToKilometers(1.0);

Static Methods Static methods are convenient because they may be called at the class level. They are typically used to create utility classes, such as the Math class in the Java Standard Library. Static methods may not communicate with instance fields, only static fields.

Overloaded Methods Two or more methods in a class may have the same name; however, their parameter lists must be different. public class MyMath{ public static int square(int number){ return number * number; } public static double square(double number){ return number * number; }

Overloaded Methods Java uses the method signature (name, type of parameters and order of parameters) to determine which method to call. This process is known as binding. The return type of the method is not part of the method signature.

Overloaded Constructors Class constructors are also methods. This means that they can also be overloaded. Overloading constructors gives programmers more than one way to construct an object of that class. All of the previous restrictions on overloading apply to constructors as well.

Revisiting The Default Constructor Java automatically provides a default constructor for a class if a constructor is not explicitly written. The default constructor provided by Java: – sets all numeric instance fields to 0, – sets all char instance fields to ‘’ (empty char). – sets all reference instance fields to null, and – sets all boolean instance fields to false.

Revisiting The Default Constructor We, as programmers, can provide a no-arg constructor. This is a constructor that accepts no arguments. If a constructor that accepts arguments is written, we should also write a no-arg constructor. If we write a no-arg constructor, we should provide the initialization of all instance fields.

Revisiting The Default Constructor InventoryItem - description : String - units : int + InventoryItem() : + InventoryItem(d : String) : + InventoryItem(d : String, u : int) : + setDescription(d : String) : void + setUnits(u : int) : void + getDescription() : String + getUnits() : int

Passing Objects as Arguments Objects can be passed to methods as arguments. Java passes all arguments by value. When an object is passed as an argument, the value of the reference variable is passed. The value of the reference variable is an address or reference to the object in memory. A copy of the object is not passed, just a pointer to the object. When a method receives a reference variable as an argument, it is possible for the method to modify the contents of the object referenced by the variable.

Passing Objects as Arguments displayRectangle(box); public static void displayRectangle(Rectangle r) { // Display the length and width. System.out.println("Length: " + r.getLength() + " Width: " + r.getWidth()); } A Rectangle object length: width: Address

Returning References From Methods Methods are not limited to returning the primitive data types. Methods can return references to objects as well. Just as with passing parameters, a copy of the object is not returned, only its address. Method return type: public static InventoryItem getData(){ … return new InventoryItem(d, u); }

Returning Objects from Methods item = getData(); public static InventoryItem getData() { … return new InventoryItem(d, u); } description: units: Pliers address A InventoryItem Object 25

The toString Method The toString method of a class can be called explicitly: Stock xyzCompany = new Stock ("XYZ", 9.62); System.out.println(xyzCompany.toString()); However, the toString method does not have to be called explicitly but is called implicitly whenever you pass an object of the class to println or print. Stock xyzCompany = new Stock ("XYZ", 9.62); System.out.println(xyzCompany);

The toString method The toString method is also called implicitly whenever you concatenate an object of the class with a string. Stock xyzCompany = new Stock ("XYZ", 9.62); System.out.println("The stock data is:\n" + xyzCompany);

The toString Method All objects have a toString method that returns the class name and a hash of the memory address of the object. We can override the default method with our own to print out more useful information.

The equals Method When the == operator is used with reference variables, the memory address of the objects are compared. The contents of the objects are not compared. All objects have an equals method. The default operation of the equals method is to compare memory addresses of the objects (just like the == operator).

The equals Method The Stock class has an equals method. If we try the following: Stock stock1 = new Stock("GMX", 55.3); Stock stock2 = new Stock("GMX", 55.3); if (stock1 == stock2) // This is a mistake. System.out.println("The objects are the same."); else System.out.println("The objects are not the same."); only the addresses of the objects are compared.

The equals Method Instead of using the == operator to compare two Stock objects, we should use the equals method. public boolean equals(Stock object2){ boolean status; if(symbol.equals(Object2.symbol && sharePrice == Object2.sharePrice) status = true; else status = false; return status; } Now, objects can be compared by their contents rather than by their memory addresses.