Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Slides:



Advertisements
Similar presentations
Spring Semester 2013 Lecture 5
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
©2004 Brooks/Cole Chapter 6 Methods. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Using Methods We've already seen examples of using methods.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
Java: How to Program Methods Summary Yingcai Xiao.
Writing methods and Java Statements. Java program import package; // comments and /* … */ and /** javadoc here */ public class Name { // instance variables.
COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007.
Classes with multiple methods Part 1. Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Chapter 7: User-Defined Methods
Introduction to Methods
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Java Unit 9: Arrays Declaring and Processing Arrays.
COMP More About Classes Yi Hong May 22, 2015.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Chapter 4 Objects and Classes.
CSCI 130 Scope of Variables Chapter 6. What is scope Parts of program which can access a variable –accessibility –visibility How long variable takes up.
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.
Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
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!
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
COMPUTER PROGRAMMING. Functions What is a function? A function is a group of statements that is executed when it is called from some point of the program.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Methods: A Deeper Look. Template for Class Definition public class { } A.Import Statement B.Class Comments C.Class Name D.Data members E.Methods (inc.
CSCI 171 Presentation 6 Functions and Variable Scope.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
Lab 01-2 Objectives:  Writing a Java program.  How to send output to the command line console.  Learn about escape sequences.  Learn how to compile,
Java methods Methods break down large problems into smaller ones Your program may call the same method many times saves writing and maintaining same code.
1 Chapter 5: Defining Classes. 2 Basics of Classes An object is a member of a class type What is a class? Fields & Methods Types of variables: –Instance:
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
CSI 3125, Preliminaries, page 1 Compiling the Program.
Method Overloading.. Method Overloading Can two methods in a class have the same name? Two methods in a class can have the same name provided – they take.
COMP 110: Introduction to Programming Tyler Johnson Feb 16, 2009 MWF 11:00AM-12:15PM Sitterson 014.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
Lecture 08. Since all Java program activity occurs within a class, we have been using classes since the start of this lecture series. A class is a template.
CSI 3125, Preliminaries, page 1 Overloading Methods In Java it is possible to define two or more methods within the same class that share the same name,
Chapter 6 Methods Chapter 6 - Methods.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Methods What is a method? Main Method the main method is where a stand alone Java program normally begins execution common compile error, trying.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Problem of the Day  Why are manhole covers round?
Functions + Overloading + Scope
Some Assignments  Write a program which prints the following information about at least 5 persons: NAME MAIL-ID EMPLOYEE-CODE PHONE Eg. Umesh
Topic: Classes and Objects
Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Functions II
Chapter 6 Methods: A Deeper Look
An Introduction to Java – Part I, language basics
CHAPTER 6 GENERAL-PURPOSE METHODS
Announcements Assignment 2 and Lab 4 due Wednesday.
Methods/Functions.
Presentation transcript:

Classes and Methods

Classes

Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called data members Methods –Operations of a class –They operate on variables of the class

Example

Fields in Class Definition Class variables Instance variables

Fields in Class Definition Class Variable –Only one copy is shared with all the objects of the class –Shared among all objects of a class –Exists even if no object has been created –Also called as static fields –Declared using the keyword static –If value is changed, it is reflected for all objects.

Instance variables Variables associated with each object A separate value for each instance of a class For example, name, address etc.

Example Class Sphere Definition public class Sphere { // class variable static double PI=3.14; // instance variables double xCenter; double yCenter; double zCenter; double radius; }

Example

Methods in Class Definition Instance Methods Class Methods

Execute class methods even when no objects of a class exist Declared using the keyword static. Static methods Can not refer to an instance variable Example: main method Buildin methods in standard class Math

Instance Methods Can execute when objects exist. Example: calculate area()

Accessing Variables and Methods Accessing Class Methods –double rootPi = Math.sqrt(Math.PI); –Objects can also access in the same way Instance variables and methods –double ballVolume = ball.volume();

Defining Classes class Sphere { static final double PI = 3.14; //class variable with fixed value static int count = 0; // Class variable to count objects // Instance variables double radius; // Radius of a sphere double xCenter; // 3D coordinates double yCenter; // of the center double zCenter; // of a sphere // Plus the rest of the class definition... }

Defining Methods Self contained block of codes Reusable Can be executed from anywhere in the program Calling a method

Basic Structure of a method return_type methodName( arg1, arg2,..., argn ) { code here } Return Statement return return_value; // To return a value from a method

Example

Parameters and Arguments Parameter – has a name and a type –Appear in definition of the method –Defines type of value to be passed to method when called Arguments –Actual value that is passed to a method when executed –Must be consistent with the type specified in parameter definition

Example public static void main(String[] args){... x = obj.mean( 3.0, 5.0 ); } double mean( double value1, double value2 ){ double result = ( value1 + value2 )/ 2.0; return result; }

Example

Passed by Value double d = 2.0; changeMe(d); System.out.println(d); public void changeMe(double d) { //this has no effect on d outside of this method! d = 345.0; }

Passed by Value

Class Method Definition class Sphere { // Class definition as before... // Static method to report the number of objects created static int getCount() { return count; // Return current object count }

Example Class class Sphere { static final double PI = 3.14; // Class variable that has a fixed value static int count = 0; // Class variable to count objects // Instance variables double radius; double xCenter; // 3D coordinates double yCenter; // of the center double zCenter; // of a sphere // Static method to report the number of objects created static int getCount(){ return count; // Return current object count } // Instance method to calculate volume double volume() { return 4.0/3.0*PI*radius*radius*radius; } // Plus the rest of the class definition... }

class Sphere { static final double PI = 3.14; static int count = 0; // Instance variables double radius = 5.0; double xCenter = 10.0; double yCenter = 10.0; double zCenter = 10.0; // Static method to report the number of objects created static int getCount(){ return count; // Return current object count } // Instance method to calculate volume double volume() { return 4.0/3.0*PI*radius*radius*radius; } // Plus the rest of the class definition... public static void main (String[] args){ int count; double volume; count=Sphere.getCount(); System.out.println(count); Sphere s1=new Sphere(); volume=s1.volume(); System.out.println(volume); } }

The Variable this Every instance method has a variable with the name this that refers to the current object for which the method is being called void changeRadius(double radius) { // Change the instance variable to the argument value this.radius = radius; }

Initializing data members: The ordinary way class Sphere { static final double PI = 3.14; // Class variable that has a fixed value static int count = 0; // Class variable to count objects // Instance variables double radius = 5.0; // Radius of a sphere double xCenter = 10.0; // 3D coordinates double yCenter = 10.0; // of the center double zCenter = 10.0; // of a sphere // Rest of the class... }

Using Initialization Blocks There are two kinds of initialization blocks: –static initialization block –non-static initialization block

static initialization block A static initialization block is a block defined using the keyword static and is executed once when the class is loaded. A static initialization block can initialize only static data members of the class. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example: static { // whatever code is needed for initialization goes here }

static initialization block class TryInitialization { static int[] values = new int[10]; static { System.out.println("Running initialization block."); for(int i=0; i<values.length; i++) { values[i] = (int)(100.0*Math.random());} } // List values in the array for an object void listValues() { System.out.println(); // Start a new line for(int value : values) { System.out.print(" " + value); // Display values } System.out.println(); // Start a new line } public static void main(String[] args) { TryInitialization example = new TryInitialization(); System.out.println("\nFirst object:"); example.listValues(); example = new TryInitialization(); System.out.println("\nSecond object:"); example.listValues(); }} Running initialization block. First object: Second object:

Non-static initialization block –non-static initialization block is executed for each object that is created and thus can initialize instance variables in a class. –This block appears without the static keyword. { // whatever code is needed for initialization goes here } Running initialization block. First object: Running initialization block. Second object:

LAB PRACTICE Compile & execute “TryInitialization” class with static initialization and non-static initialization block. Examine its output.

LAB PRACTICE Make a class Bicycle, identify its data members for example “speed=0”, “gear=1” etc. Add methods like changeGear(int), speedUp(int), applyBrakes(), printStates() etc. Make a main method to create 2 bicycle objects and call functions of the class in the following sequence. 1.Change speed 2.Change gear 3.Print states 4.Apply brakes 5.Print states