CSC 142 Computer Science II Zhen Jiang West Chester University

Slides:



Advertisements
Similar presentations
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
Advertisements

1 Classes Overview l Classes as Types l Declaring Instance Variables l Implementing Methods l Constructors l Accessor and Mutator Methods.
1 Building Java Programs Chapter 8: Classes These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8: Classes Lecture 8-1: Intro to Classes and Objects reading:
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Methods and Constructors reading: self-checks: #1-12.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading:
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Writing Classes (Chapter 4)
Object Oriented Programming Concepts OOP – reasoning about a program as a set of objects rather than as a set of actions Object – a programming entity.
Packages. Package A package is a set of related classes Syntax to put a class into a package: package ; public class { …} Two rules:  A package declaration.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Constructors and Encapsulation reading: self-checks: #10-17.
Java Classes Appendix C © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Classes CS 21a: Introduction to Computing I First Semester,
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, this reading: self-checks: #13-17 exercises:
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
10-Nov-15 Java Object Oriented Programming What is it?
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
1 Object state: fields. Fields field: A variable inside an object that represents part of its internal state.  Each object will have its own copy of.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Polymorphism l Constructors.
CSC 142 Computer Science II Zhen Jiang West Chester University
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Methods and Constructors reading: self-checks: #1-12.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Constructors; Encapsulation reading: self-checks: #13-18,
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
More About Objects and Methods
Building Java Programs
Java Primer 1: Types, Classes and Operators
More About Objects and Methods
Instance Method Review - CIS 1068 Program Design and Abstraction
CSC240 Computer Science III
CMSC 202 Static Methods.
CSC240 Computer Science III
Classes and Objects, State and Behavior
Lecture 8-3: Encapsulation, this
Building Java Programs
Object initialization: constructors
Building Java Programs
Java Classes and Objects 3rd Lecture
Building Java Programs
Building Java Programs
More About Objects and Methods
Classes and objects Readings: 8.1.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Instance Method – CSC142 Computer Science II
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Building Java Programs
Special instance methods: toString
Building Java Programs
Classes and objects Readings: 8.1.
Building Java Programs
Building Java Programs
Dr. R Z Khan Handout-3 Classes
Building Java Programs
Building Java Programs
Lecture 8-2: Object Behavior (Methods) and Constructors
Building Java Programs
reading: 8.6 self-check: #18, exercises: #9, 14
Building Java Programs
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

CSC 142 Computer Science II Zhen Jiang West Chester University

Table of Contents Introduction to field (attribute) Public and private modifiers Accessor and mutator methods Constructor Static method Instance method Overloading Static variables Summary 211/21/2015

Fields field: A variable inside an object that represents part of its internal state. Each object will have its own copy of the data fields we declare. Declaring a field, general syntax: public ; or public = ; (with initialization)‏ Example: public class Student { public String name; // each student object has a public double gpa; // name and gpa data field } 311/21/2015

public class Point3D { public int x; public int y; public int z; } Every object of type Point3D contains three integers. Point3D objects (so far) do not contain any behavior. Class declarations are saved in a file of the same name: Point3D.java 411/21/2015

Public and private modifiers P332 Type specified as public Any other class can directly access that object by name Classes generally specified as public Instance variables usually not public Instead specify as private 11/21/20155

Dog.java Change field to private DogDemo.java 11/21/20156

7

Demonstration of need for private variables Statement such as balto.name = "Balto"; is illegal since name is private 11/21/20158

Accessor and Mutator Methods P Must also provide methods to change the values of the private instance variable Typically named setSomeValue Referred to as a mutator method When instance variables are private must provide methods to access values stored there Typically named getSomeValue Referred to as an accessor method 11/21/20159

Consider the example class with accessor and mutator methods Note the mutator method setName, setBreed, setAge Note accessor methods getName, getBreed, getAge 11/21/201510

Using the accessor and mutator methods 11/21/201511

1211/21/ public class DogDemo2 2 { 3 public static void main(String[] args) 4 { 5 Dog2 balto = new Dog2(); 6 balto.setName("Balto"); 7 balto.setAge(8); 8 balto.setBreed("Siberian Husky"); 9 balto.writeOutput(); Dog2 scooby = new Dog2(); 12 scooby.setName("Scooby"); 13 scooby.setAge(42); 14 scooby.setBreed("Great Dane"); 15 System.out.println(scooby.getName()+" is a "+scooby.getBreed()+"."); 16 System.out.print("He is " + scooby.getAge() + " years old, or "); 17 int humanYears = scooby.getAgeInHumanYears(); 18 System.out.println(humanYears + " in human years."); 19 } 20 } 21 Tedious

We want something more like: // better! Dog3 balto = new Dog3(“ Balto ”, “ Siberian Husky ”, 8); 1311/21/2015

Constructor constructor: A special method that initializes the state of new objects as they are created. Constructor syntax, p352: public ( ) { ; } How does this differ from previous methods? Method name No return! 1411/21/2015

public class Dog3 { private String name; private String breed; private int age; public Dog3( String strName, String strBreed, int intAge) { name = strName; breed = strBreed; age = intAge; } 1511/21/2015

11/21/201516

11/21/201517

Calling method from constructor: a constructor can call methods within its method body, in order to avoid unnecessarily repeating some code. To avoid the problem with inheritance, which we will cover later, we need to make such a method private! 1811/21/2015

Static Methods Some methods may have no relation to any type of object, p501 One method each class Example Compute max of two integers Convert character from upper- to lower case Static method declared in a class Can be invoked without using an object Instead use the class name 11/21/201519

Adding Method main to a Class Method main used so far in its own class Often useful to include method main within class definition To create objects of other classes To be run as a start of program For any ordinary class, method main is ignored 11/21/201520

public class Point3D { public int x; public int y; public int z; } Every object of type Point3D contains three integers. Point3D objects (so far) do not contain any behavior. Class declarations are saved in a file of the same name: Point3D.java 2111/21/2015

22 How would we translate several points? p1.x += 11; p1.y += 6; p1.z + 2; p2.x += 2; p2.y += 4; p2.z += -2; p3.x += 1; p3.y += 7; p3.z += 17; What is unsettling about this code? 11/21/2015

23 Write a static method in the client code to translate points. // Shifts the location of the given point. public static void translate( Point p, int dx, int dy, int dz) { p.x += dx; p.y += dy; p.z += dz; } Example: // move p2 translate(p2, 2, 4, 6); Question: Why doesn't the method need to return the modified point? 11/21/2015

24 Every client code (application class) that declares Point3D and wants to translate points would have to write their own static translate method! Also, the call syntax doesn't match the way we're used to interacting with objects: translate(p2, 2, 4); We want something more like: p2.translate(2, 4); 11/21/2015

25 Instance methods instance method: A method inside an object that operates on that object, p347 Declaring an object's method, general syntax: public ( ) { ; } How does this differ from previous methods? 11/21/2015

26 An object's instance methods can refer to its fields. public void translate(int dx, int dy, int dz) { x += dx; y += dy; z += dz; } How does the translate method know which x, y, z to modify? 11/21/2015

27 Each instance method call happens on a particular object. Example: p1.translate(11, 6, 2); The code for an instance method has an implied knowledge of what object it is operating on. implicit parameter: The object on which an instance method is called. 11/21/2015

28 Think of each Point3D object as having its own copy of the translate method, which operates on that object's state: Point3D p1 = new Point3D(7, 2, -2); Point3D p2 = new Point3D(4, 3, 2); p1: p2: public void translate(int dx, int dy, int dz){... } y:x: 7 2 z: -2 public void translate(int dx, int dy, int dz){... } y:x: 4 3 z: 2 11/21/2015

18 29 What happens when the following calls are made? p1.translate(11, 6, 3); p2.translate(1, 7, -10); p1: p2: public void translate(int dx, int dy, int dz){... } y:x: 7 2 z: -2 public void translate(int dx, int dy, int dz){... } y:x: 4 3 z: /21/2015

public class Point3D { public int x; public int y; public Point3D( int initialX, int initialY, int initialZ) { x = initialX; y = initialY; z = initialZ; } // Changes the location of this Point3D object. public void translate(int dx, int dy, int dz){ x += dx; y += dy; z += dz; } 3011/21/2015

31 public class PointMain3 { public static void main(String[] args) { // create two Point3D objects Point3D p1 = new Point3D(5, 2, -2); Point3D p2 = new Point3D(4, 3, 2); // print each point System.out.println("p1 is (" + p1.x + ", " + p1.y + ")"); System.out.println("p2 is (" + p2.x + ", " + p2.y + ")"); // move p2 and then print it again p2.translate(2, 4, -2); System.out.println("p2 is (" + p2.x + ", " + p2.y + ")"); } Output: p1 is (5, 2, -2)‏ p2 is (4, 3, 2)‏ p2 is (6, 7, 0)‏ 11/21/2015

32 Instead of System.out.println("p1 is (" + p1.x + ", " + p1.y + ")"); It would be nice to have something more like: System.out.println("p1 is " + p1); What does this line currently do? Does it even compile? It will print: p1 is 11/21/2015

33 When an object is printed or concatenated with a String, Java calls the object's toString method, p System.out.println("p1 is " + p1); is equivalent to: System.out.println("p1 is " + p1.toString()); Note: Every class has a toString method. 11/21/2015

34 The default toString behavior is to return the class's name followed by gibberish (as far as you are concerned). You can replace the default behavior by defining a toString method in your class. 11/21/2015

35 The toString method, general syntax: public String toString() { ; } NB: The method must have this exact name and signature (i.e., public String toString() ). Example: // Returns a String representing this Point. public String toString() { return "(" + x + ", " + y + “, “ + z + ")"; } 11/21/2015

The Math Class Provides many standard mathematical methods See in examples 11/21/201536

11/21/201537

Recall that arguments of primitive type treated differently from those of a class type May need to treat primitive value as an object Java provides wrapper classes for each primitive type, p562 Methods provided to act on values 11/21/201538

Contain useful predefined constants and methods, for instance: Integer.MAX_VALUE Double.parseDouble(“199.88”) Double.toString(199.88) Have no default constructor Programmer must specify an initializing value when creating new object Have no set methods 11/21/201539

Overloading When two or more methods have same name within the same class Java distinguishes the methods by number and types of parameters If it cannot match a call with a definition, it attempts to do type conversions A method's name and number and type of parameters is called the signature 11/21/201540

Overloading and automatic type conversion can conflict Remember the compiler attempts to overload before it does type conversion Use descriptive method names, avoid overloading 11/21/201541

P /21/201542

You must not overload a method where the only difference is the type of value returned 11/21/201543

Static Variables Are shared by all objects of a class Variables declared static final are considered constants – value cannot be changed e.g., public static final double FEET_PER_YARD = 3; Variables declared static (without final ) can be changed, p498 Only one instance of the variable exists It can be accessed by all instances of the class e.g., public static int numberOfInvocations; 11/21/201544

Static variables also called class variables Contrast with instance variables Do not confuse class variables with variables of a class type Both static variables and instance variables are sometimes called fields or data members 11/21/201545

Public and private modifier, p332 Accessor and mutator method, p337 Constructor, p352 Calling private method from constructor Static method, p501 Instance method, p347 Adding method main to a class Math class Wrapper class, p562 Overloading, p376 Static Variables, p /21/2015 Summary