Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,

Slides:



Advertisements
Similar presentations
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Advertisements

The Line Class Suppose you are involved in the development of a large mathematical application, and this application needs an object to represent a Line.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference l Parameter passing Classes, Objects, and Methods.
Classes and Objects: Recap A typical Java program creates many objects which interact with one another by sending messages. Through the objects interactions,
Road Map Introduction to object oriented programming. Classes
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Classes and Objects  A typical Java program creates many objects which interact with one another by sending messages. Through the objects interactions,
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.
CS 106 Introduction to Computer Science I 03 / 17 / 2008 Instructor: Michael Eckmann.
UML Basics & Access Modifier
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)
BPJ444: Business Programming Using Java Classes and Objects Tim McKenna
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Java Classes Appendix C © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Bryce Canyon, Utah CSE 114 – Computer Science I Objects and Reference.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
COMP 110 Worksheet review, debugger Luv Kohli September 29, 2008 MWF 2-2:50 pm Sitterson 014.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
COMP 110 Classes Luv Kohli October 1, 2008 MWF 2-2:50 pm Sitterson 014.
Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void.
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.
Classes, Interfaces and Packages
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
CS 106 Introduction to Computer Science I 03 / 22 / 2010 Instructor: Michael Eckmann.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Topics Instance variables, set and get methods Encapsulation
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Class Definitions: The Fundamentals Chapter 6 3/30/15 & 4/2/15 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Topic: Classes and Objects
Michele Weigle - COMP 14 - Spr 04 Catie Welsh February 21, 2011
Chapter 3: Using Methods, Classes, and Objects
Chapter 3 Introduction to Classes, Objects Methods and Strings
Introduction to Classes
Classes, Objects, and Methods
Defining Classes and Methods
Today’s topics UML Diagramming review of terms
Lecture 5- Classes, Objects and Methods
Object Oriented Programming in java
Defining Classes and Methods
Defining Classes and Methods
Classes, Objects and Methods
Chapter 7 Objects and Classes
Presentation transcript:

Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects, and Methods

Topic 8Classes, Objects and Methods 2 OO revision l Objects »A capsule that contains 2 important parts –State (attributes or data) l What does the object know? –Behaviour (methods or functions) l What does the object know how to do? »E.g. Cars, employee records, etc. l Class » is the definition of a kind of object (template for creating objects). »E.g. a general description of what an automobile is and what it can do »Encapsulates values & operations on those values. »Also used to group related methods, like the Math class. l Instantiate »An object that satisfies the class definition is said to instantiate the class.

Topic 8Classes, Objects and Methods 3 Class Definition Class Name: Car Data: amount of fuel speed license plate Methods (actions): increase speed: How: Press on accelerator pedal stop: How: Press on brake pedal

Topic 8Classes, Objects and Methods 4 General class syntax: modifier(s) class ClassIdentifier { classMembers } l Modifier(s) »Used to alter the behaviour of the class »public, private, static l ClassMembers »Named constants, variable declarations and/or methods »Can also be declared as public, private or static

Topic 8Classes, Objects and Methods 5 class Car { double fuelAmount = 0.0; double speed = 0.0; String licencePlate = “ “; }

Topic 8Classes, Objects and Methods 6 Instantiations of the Class Car amount of fuel: 10 litres speed: 55 km / hr licence plate: “135 XJK” amount of fuel: 14 litres speed: 0 km /hr licence plate: “SUES CAR” First Instantiation Object name: patsCar Second Instantiation Object name: suesCar Third Instantiation Object name: ronsCar amount of fuel: 2 litres speed: 75 km / hr licence plate: “351 WLF”

Topic 8Classes, Objects and Methods 7 Car Example Car Class »Says Car objects has 3 pieces of data (i.e. specifies what kind of data they have. –(litres of fuel in tank; how fast car is moving; license plate) »Class definition has no data  individual objects have the data. »Also specifies what actions (methods) the objects can take & how they accomplish those actions. –increaseSpeed –stop »All objects of the Car class have the exact same methods.

Topic 8Classes, Objects and Methods 8 Car Example continued….. Car Object »Instantiates the Car class. »Each object has a name  these are variables of type Car. –patsCar, suesCar, ronsCar

Topic 8Classes, Objects and Methods 9 Types of methods l Every method belongs to a class. l Method definitions given inside the definition of the class. l Single value methods »Used to return Java values l Void-methods »Performs some action rather than return a value. »Used to produce Java statements. »E.g. print a message or read in a value from the keyboard) and do not return a value

Topic 8Classes, Objects and Methods 10 Single-value Method Definitions: public Type_Returned Method_Name(parameters) { list of statements  must contain a return statement } public double getFuelAt() { return fuelAmount; }

Topic 8Classes, Objects and Methods 11 void Method Definitions: public void Method_Name(parameters)  HEADING { list of statements BODY } public void writeOutput() { System.out.println(“License: “ + licence); System.out.println(“Fuel: “ + fuelAmount); System.out.println(“Speed: “ + speed); return;  Can be left out }

Topic 8Classes, Objects and Methods 12 PARAMETERS l Formal parameters »Used in the method definition l Actual parameters »Value of the variable that is passed to the method when that method is called/invoked.

Topic 8Classes, Objects and Methods 13 Method invocation / Call a method Object_name.method_name(); l Method defined in a class is usually invoked using an object of that class  object calling a method

Topic 8Classes, Objects and Methods 14 CONSTRUCTORS: l Special type of method. »Not void »Does not return a value l One or more found in every class. l Has the same name as the class & it executes automatically when an object of that class is created. l Used to guarantee that the instance variables of the class are initialised to specific values. l Types of constructors »With parameters »Without parameters (known as the default constructor)

Topic 8Classes, Objects and Methods 15 Instantiating / Constructing Objects To instantiate an object, use the keyword new followed by the class’s constructor method (creates a new instance of a class). Car patsCar; // creates a new Car variable c = new Car(); // invokes the constructor method or Car patsCar = new Car();

Topic 8Classes, Objects and Methods 16 The Member Access Separator l Once you’ve constructed a car, you want to do something with it. l To access the fields or methods of the car you use the. (dot) separator. »Selects a specific member of a Car object by name. l Car patsCar = new Car(); patsCar.fuelAmount = 10.0; patsCar.speed = 55.0; patsCar.licencePlate = “135XJK “; System.out.println(c.licencePlate + “ is moving at “ + patsCar.speed + “ kms/hr”);

Topic 8Classes, Objects and Methods 17 Class file REMINDERS l Each Java class definition should be a separate file l Use the same name for the class and the file, except add ".java" to the file name l For now put all the classes you need to run a program in the same directory

Topic 8Classes, Objects and Methods 18 Standard methods for a class l Constructor methods »Methods which initialise the object when it is first created. l Reader / Get methods »Methods which allow outside codes to view or get copies of the object’s state. l Writer / Set methods »Methods which allow outside codes to assign new values for the object’s state. l Mutator methods »Methods which allow outside codes to modify the state of an object. l Query methods »Methods which test the state of an object.

Topic 8Classes, Objects and Methods 19 class Car { double fuelAmount = 0.0; double speed = 0.0; String licencePlate = “ “; void setMaxSpeed() { speed = 200.0; }

Topic 8Classes, Objects and Methods 20 SIMPLE CLASS EXERCISE!!! l Consider a simple class of objects which represent Rectangles. A brief (& shallow) analysis will reveal the state & behaviour of our simple Rectangle objects. l The state (knows its?) »length (integer) »width (integer) l The behaviour (knows how to?) »Initialise itself »Set its length »Set its width »Return its width »Return its length »Calculate its area »Calculate its perimeter

Topic 8Classes, Objects and Methods 21 // File: Rectangle.java // A class which specifies simple Rectangle objects // Note that NONE of the members of Rectangle class // are labelled 'static' class Rectangle { // State (data variables) private int length; private int width;

Topic 8Classes, Objects and Methods 22 // Behaviour (instance methods) // Constructor public Rectangle() { length = 0; width = 0; }

Topic 8Classes, Objects and Methods 23 // Writer or Set methods public void setLength( int len ) { length = len; } public void setWidth( int wid ) { width = wid; }

Topic 8Classes, Objects and Methods 24 // Reader or Accessor methods public int getLength() { return length; } public int getWidth() { return width; }

Topic 8Classes, Objects and Methods 25 // Other services public int area() { int the_area = length * width; return the_area; } public int perimeter() { int perim; perim = 2 * (length + width); return perim; }

Topic 8Classes, Objects and Methods 26 public boolean isLegal() { if( length >= 0 && width >= 0 ) return true; else return false; } }// end class

Topic 8Classes, Objects and Methods 27 Constructor Methods l Must have same name as the class. l Does not have any return type »Not even void l Creates a new instance of the class. »Initialises all the variables & does any work necessary to prepare the class to be used. l If no constructor is exists, Java provides a generic one that takes no arguments. »Better to write your own constructor.

Topic 8Classes, Objects and Methods 28 l Can have several constructor methods. »Each constructor method must have a different header –Parameter list »Also known as overloading methods. // another constructor public Rectangle(int len, int wid) { length = len; width = wid; }

Topic 8Classes, Objects and Methods 29 Access Control l public »Variable or method is available to other programs. l private »To protect variable from external modification »No other code outside this class can directly access these variables or methods. »i.e. If you want objects in the same class to be able to get or set the value of a field or invoke a method. l protected »If you want access restricted to subclasses & members of the same package.

Topic 8Classes, Objects and Methods 30 Instance / Non-static Methods None of the methods in the Rectangle class are labelled static. l These types of methods are designed to be accessed via objects.

Topic 8Classes, Objects and Methods 31 NB!! NB!! NB!! The Rectangle source file must be compiled. »Note that the Rectangle.java file is not a program (no main method) – you can’t run it. To use this Rectangle class, you have to write another program which does have a main method. »Driver program / Client code »In this program you can create Rectangle objects and call methods in those objects. The Rectangle program and its driver program must both be compiled in the same directory.

Topic 8Classes, Objects and Methods 32 Testing Rectangles (Driver program) class RectTest { public static final void main(String[] args) { Rectangle page = new Rectangle(); page.setLength(30); page.setWidth(21); System.out.println(“The rectangle has a length of”); System.out.println(page.getLength()); System.out.println(“and a width of “); System.out.Println(page.getWidth());

Topic 8Classes, Objects and Methods 33 System.out.println(“It’s area is “); System.out.println(page.area()); System.out.println(“It’s perimeter is “); System.out.println(page.perimeter()); } //end main } // end class

Topic 8Classes, Objects and Methods 34 l Encapsulation »All data & methods of Rectangles encapsulated. –Hidden the data from outside use »Provides protection of the data from malicious access l Public Interface »Methods are all public a.k.a. the public interface to Rectangles. »Only way to deal with Rectangle objects is through their ( public ) methods.