Objects and Classes.

Slides:



Advertisements
Similar presentations
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.
Advertisements

Static Methods Static methods are those methods that are not called on objects. In other words, they don’t have an implicit parameter. Random number generation.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 2 Getting Started with Java Program development.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 2 Getting Started with Java Structure of.
School of Computing Science CMT1000 © Ed Currie Middlesex University Lecture 10: 1 TEST!!
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
1 Fall 2007ACS-1903 Chapter 3 Decision Structures Variable Scope The Conditional Operator The switch Statement DecimalFormat Class printf.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
CS 180 Recitation 8 / {30, 31} / Announcements Project 1 is out –Due 10:00pm –Start early! –Use the newsgroup for your questions –LWSN B146.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Java Programming, Second Edition Chapter Four Advanced Object Concepts.
Writing Classes (Chapter 4)
More Object Concepts Chapter 4.  Our class is made up of several students and each student has a name and test grades  How do we assign the variables.
Java Classes Using Java Classes Introduction to UML.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
OBJECT INTERACTION CITS1001. Overview Coupling and Cohesion Internal/external method calls null objects Chaining method calls Class constants Class variables.
Static Class Methods CSIS 3701: Advanced Object Oriented Programming.
1 OOP : main concepts Polymorphism. 2 OOP : main concepts  The main concepts:  In a superclass –public members Accessible anywhere program has a reference.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Session 7 Methods Strings Constructors this Inheritance.
Classes. Student class We are tasked with creating a class for objects that store data about students. We first want to consider what is needed for the.
1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables.
CSI 3125, Preliminaries, page 1 Compiling the Program.
More Object Concepts— Farrell, Chapter 4 Dr. Burns.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Building java programs, chapter 3 Parameters, Methods and Objects.
1 Chapter 6 Programming with Objects and Classes F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive.
Chapter 6 - More About Problem Domain Classes1 Chapter 6 More About Problem Domain Classes.
 2003 Prentice Hall, Inc. All rights reserved. 1 Will not cover 4.14, Thinking About Objects: Identifying Class Attributes Chapter 4 - Control Structures.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
Classes - Intermediate
Data Types – Reference Types Objective To understand what reference types are The need to study reference types To understand Java standard packages To.
OOP Basics Classes & Methods (c) IDMS/SQL News
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Java 5 Class Anatomy. User Defined Classes To this point we’ve been using classes that have been defined in the Java standard class library. Creating.
Methods. Methods are groups of statements placed together under a single name. All Java applications have a class which includes a main method class MyClass.
User-Written Functions
Classes and Objects.
Chapter 7 User-Defined Methods.
Data Types – Reference Types
Arrays 3/4 By Pius Nyaanga.
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
Some Eclipse shortcuts
Objects, Classes, Program Constructs
Dialogues and Wrapper Classes
HKCT Java OOP Unit 02 Object Oriented Programming in Java Unit 02 Methods, Classes, and Objects 1.
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
Class Structure 16-Nov-18.
Lecture 11 C Parameters Richard Gesick.
Pass by Reference, const, readonly, struct
CSC 113 Tutorial QUIZ I.
Defining Your Own Classes
Phil Tayco Slide version 1.0 Created Oct 9, 2017
CHAPTER 6 GENERAL-PURPOSE METHODS
Class Structure 7-Dec-18.
Object Oriented Programming
Class Structure 2-Jan-19.
Introduction to Java Programming
CS360 Client/Server Programming Using Java
Classes, Objects and Methods
Arrays 3/4 June 3, 2019 ICS102: The course.
Chapter 6 Arrays.
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Objects and Classes

Objects and Classes So far we have written applications with a single class. These applications have made use of various Java library classes such as System and JOptionPane. Apart from exercises 2.2 and 2.3 the only objects we have used have been Strings and the standard output stream System.out.

Date demonstration application 01 import static javax.swing.JOptionPane.*; 02 import java.util.*; 03 import java.text.DecimalFormat; 04 class DateDemo 05 { 06 public static void main(String[] args) 07 { 08 Calendar now = new GregorianCalendar(); 09 DecimalFormat twoDigits = new DecimalFormat("00"); 10 int year = now.get(Calendar.YEAR); 11 int month = now.get(Calendar.MONTH) + 1; 12 int day = now.get(Calendar.DATE); 13 int hour = now.get(Calendar.HOUR_OF_DAY); 14 int minute = now.get(Calendar.MINUTE); 15 int second = now.get(Calendar.SECOND);

Date demonstration application 16 showMessageDialog(null, 17 "It is now " + twoDigits.format(hour) + ":" + 18 twoDigits.format(minute) + ":" + 19 twoDigits.format(second) + " on " + 20 twoDigits.format(day) + "/" + 21 twoDigits.format(month) + "/" + 22 year); 23 } 24 } This is the output when the program was run on Sunday afternoon, 4th September 2005

Date demonstration application 01 import static javax.swing.JOptionPane.*; 02 import java.util.*; 03 import java.text.DecimalFormat; These lines are needed to import the Java library classes JOptionPane, Calendar, GregorianCalendar and DecimalFormat. (Actually, Calendar is an interface – see later)

Date demonstration application 08 Calendar now = new GregorianCalendar(); This line declares a Calendar variable now and assigns to it a new GregorianCalendar object. GregorianCalendar() is the no-argument constructor of the GregorianCalendar class which returns the current date and time (to the nearest second). This class has many other constructors for creating GregorianCalendar objects

Date demonstration application 09 DecimalFormat twoDigits = new DecimalFormat("00"); This line declares a DecimalFormat variable twoDigits and assigns to it a new DecimalFormat object. DecimalFormat(String pattern) is the constructor of the DecimalFormat class that has a String formatting argument. These format strings can be quite complex; here we simply want to be able to format an int using exactly two digits so that 9 becomes 09 etc.

Date demonstration application int hour = now.get(Calendar.HOUR_OF_DAY); get(…) is a dynamic method of Calendar. Here it is used on the now object to return the current hour in the range 0 to 23.

Date demonstration application 16 JOptionPane.showMessageDialog(null, 17 "It is now " + twoDigits.format(hour) + ":" + 18 twoDigits.format(minute) + ":" + 19 twoDigits.format(second) + " on " + 20 twoDigits.format(day) + "/" + 21 twoDigits.format(month) + "/" + 22 year); 23 } 24 } format(hour) etc is a dynamic method of class DecimalFormat. Because of the way twoDigits was defined this returns hours etc formatted using two digits, with a leading 0 if hours etc is less than 10.

get and set methods Library classes often have methods named getXXX to return part of the internal state of an object. Many library classes also provide setXXX methods to alter part of the internal state of an object. For instance the Calendar class there are nine such methods. Note that we have no idea exactly how date/times are represented internally, nor do we need to know this.

Calling dynamic methods In Java we call a dynamic method on an object using objectName.methodName(arguments) This is also called sending a message to the object.

Design diagrams The library classes are shown for illustration only – they are fully documented in the Java SDK. Note that the DateDemo class has no methods of its own other than main (The diagrams on page 42 of the workbook are incorrect – sorry!

Car repair app – main class 01 import javax.swing.*; 02 import java.text.DecimalFormat; 03 class CarRepairApp 04 { 05 public static void main(String[] args) 06 { 07 DecimalFormat pounds = new DecimalFormat("£#,##0.00"); 08 String partsStr = read("What is the parts cost"); 09 String hoursStr = read("How many hours"); 10 double parts = Double.parseDouble(partsStr); 11 double hours = Double.parseDouble(hoursStr); 12 CarRepair myRepair = new CarRepair(parts, hours); 13 double bill = myRepair.calculateBill(); 14 display("Your bill is " + pounds.format(bill)); 15 }

Car repair app – main class 17 private static void display(String s) 18 { 19 JOptionPane.showMessageDialog(null, s); 20 } 21 22 private static String read(String prompt) 23 { 24 return JOptionPane.showInputDialog(prompt); 25 } 26 } The main class uses a DecimalFormat object (declared at line 07, used at line 14) and a CarRepair object (declared at line 12, used at line 13) We must write the CarRepair class separately and place it in the same folder.

CarRepair class 01 class CarRepair 02 { 03 private double parts; 04 private double hours; 05 private static final double HOURS_COST = 20; 06 private static final double VAT = 17.5; 07 08 CarRepair(double p, double h) 09 { 10 parts = p; 11 hours = h; 12 } 13 14 public double calculateBill() 15 { 16 double bill = parts + hours * HOURS_COST; 17 return bill * (1 + VAT / 100); 18 } 19 20 }

CarRepair class The CarRepair class has: double instance variables parts and hours a constructor CarRepair(double p, double h) that assigns p to parts and h to hours a public double calculateBill() method to calculate the bill constants for the hourly cost and the rate of VAT

CarRepair class When we use the CarRepair class we create an instance of it in the main application called myRepair at line 12. This is created by the constructor at lines 08 – 12 in the CarRepair class. The values passed across to parameters p and h are the values of parts and hours in the main program. Remember that there is no need to use the same variable names in the main application and the CarRepair class, but it is convenient to do so.

CarRepair class diagrams

Carpet calculator with a class For a more substantial example, see classes CarpetCalculatorApp and CarpetCalculator pp. 40 – 44 of the notes. This example shows how you can design your auxiliary class by first writing the application class to see what is needed.

Instance variables When designing a class to create objects, we need first to consider what data types make up each individual object. These are called the instance variables of the class. They have the entire class as their scope so they are available to all the methods. They are nearly always private. The private instance variables for the CarRepair class are two doubles, parts and hours

Constructors and dynamic methods All classes should have at least one constructor. A constructor is a special method whose job is to create new objects belonging to the class by assigning values to the instance variables. Here is the CarRepair constructor: 08 CarRepair(double p, double h) 09 { 10 parts = p; 11 hours = h; 12 }

Constructors and dynamic methods There is just one public dynamic method for the CarRepair class: 14 public double calculateBill() 15 { 16 double bill = parts + hours * HOURS_COST; 17 return bill * (1 + VAT / 100); 18 }

The default constructor It is possible to define a class without specifying a constructor. For instance the application classes we have seen so far have had no constructors because we don’t use them to create objects, they are there as a starting point for running the application via their main method. If we have a class MyClass.java without a constructor, Java assumes there is a default constructor with no arguments, which does nothing other than creating an object: MyClass() { }

The default constructor If a default constructor is used, the object has a possibly unsafe state as its instance variables are not set, so you should provide set methods to give new objects a sensible state. What do you think the values of String, int and double instance variables would be if the default constructor is used? Relying on the default constructor is regarded as bad practice! If you provide any other constructor, Java does not recognize the default.

The default constructor See the notes pp 50-51for a version of the Car Repair application where the CarRepair class has no constructor.