Defining Classes and Methods Chapter 4.1. Key Features of Objects An object has identity (it acts as a single whole). An object has state (it has various.

Slides:



Advertisements
Similar presentations
Spring Semester 2013 Lecture 5
Advertisements

IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Chapter 4 Defining Classes I Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 41 Defining Classes and Methods Chapter 4.
Introduction to Programming with Java, for Beginners Intro OOP with Java Java Program Structure.
Slides prepared by Rose Williams, Binghamton University Chapter 1 Getting Started 1.1 Introduction to Java.
Chapter 4 Defining Classes I Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Java An introduction. Example 1 public class Example1 { public static void main (String [] args) { System.out.println (“This is the first example”); int.
Advanced Java and Android Day 1 Object-Oriented Programming in Java Advanced Java and Android -- Day 11.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Introduction to Methods
Unit 2: Java Introduction to Programming 2.1 Initial Example.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Intro to CS – Honors I Classes and Methods GEORGIOS PORTOKALIDIS
COMP More About Classes Yi Hong May 22, 2015.
Shorthand operators.
Hello AP Computer Science!. What are some of the things that you have used computers for?
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Classes, Objects, and Methods
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
4.1 Instance Variables, Constructors, and Methods.
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.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
1 Objects and Classes. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 8 Objects and Classes.
Classes CS 21a: Introduction to Computing I First Semester,
FIRST JAVA PROGRAM. JAVA PROGRAMS Every program may consist of 1 or more classes. Syntax of a class: Each class can contain 1 or more methods. public.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
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.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
Objects and Classes Mostafa Abdallah
Defining Classes and Methods Chapter 4. Object-Oriented Programming Our world consists of objects (people, trees, cars, cities, airline reservations,
Chapter 41 Defining Classes and Methods Chapter 4.
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.
COMP 110: Introduction to Programming Tyler Johnson Feb 16, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Methods.
Methods main concepts – method call – object 's methods – actual parameters – method declaration – formal parameters – return value other concepts – method.
OOP Basics Classes & Methods (c) IDMS/SQL News
Chapter 3 Implementing Classes
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
Java Primer 1: Types, Classes and Operators
Methods.
Classes, Objects, and Methods
Defining Classes and Methods
Group Status Project Status.
Chapter 4 Defining Classes I
Defining Classes and Methods
Introduction to Object-Oriented Programming
Defining Classes and Methods
Chapter 9 Objects and Classes Part 01
Classes, Objects and Methods
Announcements Assignment 2 and Lab 4 due Wednesday.
OO Programming Concepts
Corresponds with Chapter 5
Presentation transcript:

Defining Classes and Methods Chapter 4.1

Key Features of Objects An object has identity (it acts as a single whole). An object has state (it has various properties, which might change). An object has behavior (it can do things and can have things done to it). An object belongs to a class. (cf. Object-oriented Analysis and Design, by Grady Booch, Addison-Wesley, 1994.)

Objects of a Class

Basic Terminology Objects can represent almost anything. A class defines a family of objects. –It specifies the kinds of data an object of the class can have. –It provides methods specifying the actions an object of the class can take. An object is an instance of the class. We will call the data items associated with an object the instance variables of that object (i.e. that instance of the class).

Object Oriented Programming: three stages Creating the program: –define classes that describe objects that the program will use when it is running. –including one class that contains the static main() method which is used to start the program running Compiling the program –translation to bytecode Running the program –The java interpreter looks for a static main() method and starts running. –The program does its work by creating objects and invoking their methods. The order of creation and invocation depends upon the problem at hand.

Class Files and Separate Compilation Each Java class definition should be in a file by itself. A Java class can be compiled before it is used in a program If all the classes used in a program are in the same directory (folder) as the program file, you do not need to import them.

Syntax of Class Definitions class ClassName { Descriptions of the instance variables and methods each object will have and the constructors that initialize a new object. }

Class Definition Often the class definition is segmented for clarity as follows class ClassName { // Description of the variables. // Description of the constructors. // Description of the methods }

Checkpoint A program is a class that has a method named main Does every class require a main( ) method?

Object Oriented Hello class HelloObject { // method definition void speak() { System.out.println("Hello from an object!"); } } class HelloTester { // method definition public static void main ( String[] args ) { HelloObject anObject = new HelloObject(); anObject.speak(); }

What Happens class HelloObject { // method definition void speak() { System.out.println("Hello from an object!"); } } class HelloTester { // method definition public static void main ( String[] args ) { HelloObject anObject = new HelloObject(); anObject.speak(); } 1 main starts running 2 New HelloObject is created 3 it is assigned to anObject 4 speak method of anObject is invoked. 5 A message is printed on the screen. 6. The program finishes

speak( ) method requires anObject to contain it

Methods and Objects In general, methods require an object to be present in order to be invoked. However, this is not always the case. Static methods can be invoked by themselves. main is an example of a static method

More Complex Example SpeciesFirstTry.java This a class which defined three methods.SpeciesFirstTry.java SpeciesFirstTryDemo.java This is another class which invokes the first one.SpeciesFirstTryDemo.java Both definitions live in the same directory (folder) – so there is no need for the second to import the first.

Two Kinds of Method methods that return a single value (e.g. nextInt ) methods that perform some action other than returning a single value (e.g println ), called void methods

Aspects of Methods Methods Definition Methods that return a value Void Methods Invocation Methods that Return a value Void Methods

void Method Definitions example public void writeOuput() { System.out.println(“Name: “ + name); System.out.println(“Age: “ + age); } Such methods are called void methods.

Definition of Methods That Return a Value example public int fiveFactorial(); { int factorial = 5*4*3*2*1; return factorial; } As before, the method definition consists of the method heading and the method body. –The return type replaces void.

Method Definitions, cont. The parentheses following the method name contain any information the method needs. public int fiveFactorial(); In this case there is no information since there is nothing between parentheses Sometimes, however, we do include such information in the form of a parameter list e.g. public int sum(int i, j); The parameter list gives the order and types of arguments This first part of the method definition is called the heading. The remainder of the method is called the body, and is enclosed in braces {}.

Defining Methods That Return a Value, cont. The body of the method contains declarations and statements. The body of the method definition must contain return Expression; –This is called a return statement. –The Expression must produce a value of the type specified in the heading.

Using return in a void Method A void method is not required to have a return statement. However, it can be user to terminate the method invocation before the end of the code, to deal with some problem, form return;

Invocation of Methods that Return a Value example int next = keyboard.nextInt(); –keyboard is the calling object. –keyboard.nextint() is the invocation. –You can use the invocation any place that it is valid to use of value of the type returned by the method.

Invocation of Methods that Do Not Return a Value example System.out.println(“Enter data:”); –System.out is the calling object. –System.out.println() is the invocation. The method invocation is a Java statement that produces the action(s) specified in the method definition. It is as if the method invocation were replaced by the statements and declarations in the method definition.

Variables A class definition is associated with different kinds of variables. –variables that are declared in the class –variables that declared in the methods defined within the class.

The Class Bank Account public class BankAccount { public double amount; public double rate; public void showNewBalance( ) { double newAmount = amount + (rate/100.0)*amount; System.out.println("amount is $" + newAmount); }

Variables When an instance of a class is created, a new instance of each variable declared in the class is created. These variables are instance variables. Instance variables declared to be public can be accessed from outside the class.

Accessing Instance Variables Outside the class definition, a public instance variable is accessed with –objectname. instancevariable name aBankAccount.rate = 10; Inside the definition of the same class only the name of the instance variable is used. amount + (rate/100.0)*amount

Use of this Inside the definition of the same class only the name of the instance variable is used. amount + (rate/100.0)*amount Equivalently this stands for the calling object - the object that invokes the method. this.amount + (this.rate/100.0) * this.amount

Local Variables Variables that belong to the methods are private to the method. They are called local variables They cannot be accessed from outside the method in which they are defined.

Identify the Local Variable public class BankAccount { public double amount; public double rate; public void showNewBalance( ) { double newAmount = amount + (rate/100.0)*amount; System.out.println("amount is $" + newAmount); } local variable instance variables

What is the Output? public class LocalVariablesDemoProgram { public static void main(String[] args) { BankAccount myAccount = new BankAccount( ); myAccount.amount = ; myAccount.rate = 5; double newAmount = ; myAccount.showNewBalance( ); System.out.println("I wish my new amount were $" + newAmount); }

Blocks The terms block and compound statement both refer to a set of Java statements enclosed in braces {}. A variable declared within a block is local to the block. –When the block ends, the variable disappears. If you intend to use the variable both inside and outside the block, declare it outside the block.

Local Varables { int x = 1, y = 2; { int x = 3; x = x + y; System.out.println(x); } x = x + y; System.out.println(x); }

Constructors Every class is associated with one or more constructors. A constructor is a method which constructs an instance of a class. Below a constructor invocation is shown in red BankAccount ac = new BankAccount( )

Default Constructor If a constructor is not defined explicitly within the class definition, it receives a default definition. The default definition is a method without arguments whose name is the same as that of the class. The default constructor behaves as though it were defined as shown in red.

Default Constructor class HelloObject { HelloObject() // default constructor { } void speak() { System.out.println("Hello from an object!"); } } Because the default constructor exists we can write new HelloObject(). Note that it has an empty argument list.

Improving HelloObject – Step 1 The first step is to provide the speak method with a variable, in this case greeting, to hold the greeting string. class HelloObject { String greeting; void speak() { System.out.println(greeting); } How does greeting receive a value?

Assigning to greeting What we want is to be able to write something like this: { hello = new HelloObj(“hello”), goodbye = newHelloObj(“goodbye”); hello.speak(); goodbye.speak(); } In other words, we want to convey information to the object through parameters of the constructor. The problem is that the default constructor for HelloObj has no parameters.

The instance variable has to be set by the constructor – which means that the constructor has to have one parameter. We therefore cannot use the default constructor, and have to write our own. Further details are given in Kjell Chapter 30Kjell Chapter 30

How Values are Transmitted The method invocation, e.g. HelloObject(″Goodbye″) evaluates the supplied argument (actual parameter) The value of the argument is assigned to the method's corresponding formal parameter. The method computes with the parameter set to that value. This is known as the call-by-value mechanism.