Lecture 6 D&D Chapter 7 & 8 Intro to Classes and Objects Date.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Advertisements

Chapter 6: A First Look at classes. Object-Oriented Programming  Object-oriented programming is centered on creating objects rather than procedures.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
Chapter 5 Part 1 COSI 11a Prepared by Ross Shaull.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
Chapter 6: A First Look at Classes
UML Basics & Access Modifier
Centre for Computer Technology ICT115 Object Oriented Design and Programming Week 2 Intro to Classes Richard Salomon and Umesh Patel Centre for Information.
A First Look At Classes Chapter 6. Procedural Programming In procedural- programming all the program functionality is written in a few modules of code.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: From Control Structures through Objects Third Edition.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Starting Out with Java: From Control Structures through Objects.
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!
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
© 2010 Pearson Addison-Wesley. All rights reserved. 6-1 Chapter Topics Chapter 6 discusses the following main topics: –Classes and Objects –Instance Fields.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 3 A First Look at Classes and Objects.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Starting Out With Java 5 Control Structures to Objects By Tony Gaddis Copyright © 2005, 2005 Pearson Addison-Wesley. All rights reserved. Chapter 6 Slide.
Topics Instance variables, set and get methods Encapsulation
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Introduction of Object Oriented Programming.
CS16: UML’s Unified Modeling Language. UML Class Diagram A UML class diagram is a graphical tool that can aid in the design of a class. The diagram has.
1 More About Derived Classes and Inheritance Chapter 9.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 3: A First Look at Classes and Objects.
Chapter 6 A First Look at Classes. 2 Contents 1. Classes and objects 2. Instance Fields and Methods 3. Constructors 4. Overloading Methods and Constructors.
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Lecture 7 D&D Chapter 7 & 8 Composite Classes and enums Date.
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
Lecture 14 Throwing Custom Exceptions
Inheritance ITI1121 Nour El Kadri.
Java: Base Types All information has a type or class designation
Chapter 3 Classes & Objects
A first Look at Classes.
Methods Attributes Method Modifiers ‘static’
classes and objects review
Introduction to Classes
Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.
CompSci 230 Software Construction
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
CS 200 Creating Classes Jim Williams, PhD.
Introduction to Classes
Encapsulation and Constructors
Chapter 9 Objects and Classes
Object Oriented Programming
Variables Title slide variables.
Today’s topics UML Diagramming review of terms
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Lecture 5- Classes, Objects and Methods
Java Programming with BlueJ Objectives
CS 200 Creating Classes Jim Williams, PhD.
CS 200 Creating Classes Jim Williams, PhD.
Lecture 8 Object Oriented Programming (OOP)
Review for Midterm 3.
Chapter 6: A First Look at classes
Object-Oriented Design AND CLASS PROPERTIES
Presentation transcript:

Lecture 6 D&D Chapter 7 & 8 Intro to Classes and Objects Date

Goals Instance variables (with getter and setter methods) Methods By the end of this lesson, you should know how to process strings in Java know how to define and use a class that has Instance variables (with getter and setter methods) Methods Constructor

Strings Strings Classes Instance variables Setters and getters Strings in Java are a special class of objects (class/type String). That is, they don’t just store a string of characters, but also provide methods that operate on that string. Here are some examples: String a = "Hello World!"; // Note: Double quotes! System.out.println(a); String b = "Aotea"; String c = "roa"; System.out.println(b+c); // String concatenation with + // Double quotes in strings: System.out.println( "Aoteaora is also known as \"New Zealand\""); // Measure string length with the length() method: System.out.println(b + " has " + b.length() + " letters"); System.out.println(b + c + " has " + (b+c).length() + " letters"); // You can also use methods on string literals: System.out.println("shout!".toUpperCase()); String d = b + c; // Getting at substrings is easy: System.out.println("Is there " + d.substring(2, 5) + " in " + d + "?"); // String lengths can change! d += " aka New Zealand"; System.out.println(d + " has " + d.length() + " letters"); Strings Classes Instance variables Setters and getters Constructors Using objects Summary

String comparison Strings Classes Instance variables Comparing strings for identical content is a common task in programming. In Java, this can be a bit of a pitfall: String x = "Black"; String y = "White"; // This seems to work: if (x == y) { System.out.println(x + " is " + y); } else { System.out.println(x + " is not " + y); } y = "Black"; // Not really, though! String z1 = "Aotea"; String z2 = "Ao"; z2 += "tea"; if (z1 == z2) { System.out.println(z1 + " is " + z2); System.out.println(z1 + " is not " + z2); Strings Classes Instance variables Setters and getters Constructors Using objects Summary

String comparison Strings Classes Instance variables What went wrong here? Remember that strings in Java are objects. Object variables are really just the memory addresses of the objects. When we use ==, Java compares the memory addresses of the objects on either side of the ==. z1 and z2 are different objects with the same content, and are located at different addresses in memory. When we store a string literal like "Black" or "White" in a String object, the Java VM tries to be efficient and stores the string literal only once, even if we assign it to a second variable. If we create a string by concatenation, the VM doesn’t spot that we have just re-created the same string again and so stores it in two independent objects. There’s got to be a better way than the comparison operators, and there is: the equals() method! if (z1.equals(z2)) { … Strings Classes Instance variables Setters and getters Constructors Using objects Summary

Class Example Rectangle +length: double +width: double +area: double Strings Classes Instance variables Setters and getters Constructors Using objects Summary I want to have a class Rectangle from which I can instantiate various Rectangle objects (i.e., different rectangles). Here’s the UML class diagram. My Rectangle class will have 3 attributes: length, width and area, and one method diagonal(), which will return the length of the rectangle’s diagonal. Rectangle +length: double +width: double +area: double +diagonal(): double

Attributes and instance variables Strings Classes Instance variables Setters and getters Constructors Using objects Summary A class attribute (e.g., the length of a rectangle) normally becomes an instance variable. That is to say each Rectangle object has its own length. Instance variables are considered private to the object, so we define methods to get and set the values that are public. In object jargon, these methods are known as getters and setters, or sometimes as accessors and mutators (perhaps because this sounds more sophisticated?). In our case, the area of a Rectangle depends on its width and length, though. So if we store the area in an instance variable as well, we could end up with an inconsistent object. Code outside the Rectangle class setLength() myRectangle1 length = 10; width = 20; getLength()

Re-cap: Make a class Put the class in its own .java file. For these little projects, we have the classes in the same project and package (right click on the project name and select New/Class). Don’t tick the main() box. Our main() method will be in a different class. You get an empty class: public class Rectangle { } Next we add the instance variables and their getters and setters Strings Classes Instance variables Setters and getters Constructors Using objects Summary

Instance Variables Instance variables Setter for length Strings Classes Instance variables Setters and getters Constructors Using objects Summary public class Rectangle { private double length; private double width; public void setLength(double length) { this.length = length; } public double getLength() { return length; public void setWidth(double width) { this.width = width; public double getWidth() { return width; Instance variables Setter for length Getter for length Setter for width Getter for width

this Instance variable Parameter Instance variable Parameter Strings public class Rectangle { private double length; private double width; public void setLength(double length) { this.length = length; } Instance variable Strings Classes Instance variables Setters and getters Constructors Using objects Summary Parameter Instance variable Parameter Notice setLength uses length as the method parameter. This will show in the auto-prompt in Eclipse thus reminding us of what to pass. However, we now have two variables called length: the class instance variable and the method parameter. The method parameter is the one in scope and hides the instance variable. So we need another way to refer to the class instance: We use the keyword this: this.length to access the instance variable. Leaving the this. off creates a warning (orange underline) but NOT an error. So the program will run – it just won’t assign the value to the instance variable. Instead, it will assign the value of the parameter back to the parameter.

Why use setters and getters? Strings Classes Instance variables Setters and getters Constructors Using objects Summary Why are we using getters and setters here to access instance variables? After all, we could simply declare the instance variables public, right? Also, calling methods always takes longer than just storing a value. So why are we doing it the cumbersome way here? A lot of textbooks don’t mention this (Deitel and Deitel does). Setters let us do things before we store the data passed to it: validate (e.g., for correct range), convert (e.g., store a value passed in NZ$ internally in US$), perform actions associated with the change of value (e.g., repaint a graphical object whose colour value we change). Getters let us do things when we read data: convert, register the access, etc. By using getters and setters from the start, we ensure that we can always add this functionality later. public class Rectangle { public double length; public double width; … }

A setter and getter for the area Strings Classes Instance variables Setters and getters Constructors Using objects Summary Setters and getters don’t always need an underlying private instance variable. Here, we use our two existing instance variables to store any area value we pass. Since the area of a rectangle only tells us what the product of its length and width is, but not what the length and the width themselves are, we get to choose how to resolve this in setArea(). Here, we choose to make the rectangle a square whenever we set the area. getArea() returns a computed value. public class Rectangle { … public void setArea(double area) { length = Math.round(Math.sqrt(area)); width = length; } public double getArea() { return length*width;

this refers to the overloaded constructor Constructor Methods Classes have constructors – these are special methods evoked when you instantiate a new Object. A constructor: Has the same name as the class Doesn’t have a return value – it automatically returns the object. Can be overloaded. Can call other overloaded constructors with this(…); Rectangle has 3 constructors, 1. The default constructor, makes a square of area 1. 2. Sets the length and width as the object is instantiated. 3. Makes a square of the given area. Strings Classes Instance variables Setters and getters Constructors Using objects Summary public Rectangle() { this(1,1); } public Rectangle(double length, double width) { this.length = length; this.width = width; public Rectangle(double area) { this(Math.round(Math.sqrt(area)), Math.round(Math.sqrt(area))); this refers to the overloaded constructor

Other Methods Strings Classes Instance variables Setters and getters Any other methods are defined in the standard way. private for those just available to the objects public for those available to any object of the class (most frequent). public static for those available directly from the class without the object being instantiated. This method returns the length of a Rectangle’s diagonal: public class Rectangle { … public double diagonal() { return Math.sqrt(length*length+width*width); } Strings Classes Instance variables Setters and getters Constructors Using objects Summary

Instantiating (Making) Rectangles Now we create another class RectangleExamples. Add a main() to it and instantiate a few rectangles: public static void main(String[] args) { Rectangle r1 = new Rectangle(); // just a 1 x 1 square Rectangle r2 = new Rectangle(4); // a 2 x 2 square Rectangle r3 = new Rectangle(6,4); // a 6 x 4 rectangle System.out.println("r1 is a " + r1.getLength() + " by " + r1.getWidth() + " with area " + r1.getArea() + " and diagonal " + r1.diagonal() ); System.out.println("r2 is a " + r2.getLength() + " by " + r2.getWidth() + " with area " + r2.getArea() + " and diagonal " + r2.diagonal() System.out.println("r3 is a " + r3.getLength() + " by " + r3.getWidth() + " with area " + r3.getArea() + " and diagonal " + r3.diagonal() } Strings Classes Instance variables Setters and getters Constructors Using objects Summary

A bunch of rectangles! Strings Classes Instance variables Well, an ArrayList really: ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>(); rectangles.add(r1); rectangles.add(r2); rectangles.add(r3); for (Rectangle r: rectangles) { System.out.println("We have a " + r.getLength() + " by " + r.getWidth() + " with area " + r.getArea() + " and diagonal " + r.diagonal() ); } Strings Classes Instance variables Setters and getters Constructors Using objects Summary

Debug Strings Classes Instance variables Setters and getters Constructors Using objects Summary

What do we know Strings Classes Instance variables Setters and getters Constructors Using objects Summary A class Is in its own .java file (at this stage) Its attributes become Private instance variables with Each with a get and a set method Use this. to change the instance variable A class can have one or more Constructor methods they Are the same name as the class Do not have a return type specified Often set some of the attributes of the newly instantiated object Constructors can call each other using this() A class can have both private and public methods that receive and return values Static variables and methods are Class elements and there is only one of them for all of the objects of that class. The class is now a java type available in your project. You can use it to instantiate objects You can use your new type in much the same way as any other type – e.g. make an ArrayList of the objects

Resources Review questions in chapter 7 or D& D D&D chapter 7& 8, also 14.1 to 14.3 https://docs.oracle.com/javase/tutorial/java/javaOO/ Homework. Review questions in chapter 7 or D& D Play with example program. Add another class ‘Triangle’, give it some attributes and methods. Look at what is going on with debug.

Next Lecture D&D Chapters 7 & 8 Objects (2) enums