Sahar Mosleh California State University San MarcosPage 1 Classes and Objects and Methods.

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
ECE122 Feb Introduction to Class and Object Java is an object-oriented language. Java’s view of the world is a collection of objects and their.
Classes and Instances. Introduction Classes, Objects, Methods and Instance Variables Declaring a Class with a Method and Instantiating an Object of a.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
1 Memory Model of A Program, Methods Overview l Memory storage areas for an executing program l Introduction to methods and methods definitions l General.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Introduction to Methods
Department of Computer Science
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Chapter 2 How to Compile and Execute a Simple Program.
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.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Sahar Mosleh California State University San MarcosPage 1 System.out.println for console output System.out is an object that is part of the Java language.
©Silberschatz, Korth and Sudarshan1 Methods Method Basics Parameters Void vs. Non-void Methods Recursion.
Sahar Mosleh California State University San MarcosPage 1 A for loop can contain multiple initialization actions separated with commas Caution must be.
1. 2 Reference... Student stu; Reference of Student stu When the reference is created it points to a null value. Before access the reference, objects.
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 F Hello World! F Java program compilation F Introducing Methods F Declaring Methods F Calling Methods F Passing Parameters by value F Overloading.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
ECE122 Feb. 22, Any question on Vehicle sample code?
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
Sahar Mosleh California State University San MarcosPage 1 Program Control Statement.
Classes One class usually represents one type of object –May contain its own member variables –May contain its own methods to operate on the member variables.
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.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Sahar Mosleh California State University San MarcosPage 1 The Class String There is no primitive type for strings in Java The class String is a predefined.
COMP 110 Classes Luv Kohli October 1, 2008 MWF 2-2:50 pm Sitterson 014.
The assignment expressions. The assignment operator in an assignment statement We have seen the assignment statement: Effect: var = expr; Stores the value.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Methods Methods are how we implement actions – actions that objects can do, or actions that can be done to objects. In Alice, we have methods such as move,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
L EC. 06: C LASS D ETAILS S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length.
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.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 5 GEORGE KOUTSOGIANNAKIS Copyright: FALL 2015 Illinois Institute of Technology- George Koutsogiannakis 1.
1 Class 1 Lecture Topic Concepts, Definitions and Examples.
Sahar Mosleh California State University San MarcosPage 1 Character String.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Classes, Interfaces and Packages
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
1 Class and Object Lecture 7. 2 Classes Classes are constructs that define objects of the same type. A Java class uses instance variables to define data.
Methods.
Programming Fundamentals Enumerations and Functions.
Methods, classes, and Objects Dr. Jim Burns. Question  Which of the following access modifiers is the default modifier?  public  private  protected.
2015 Spring Content Class method [review] Access control
Topic: Classes and Objects
Yanal Alahmad Java Workshop Yanal Alahmad
User-Defined Functions
Introduction to Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
Classes, Objects, and Methods
Chapter 6 Methods: A Deeper Look
Object-Oriented Programming
OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
Classes One class usually represents one type of object
Object Oriented Programming in java
Introduction to Object-Oriented Programming
Classes, Objects and Methods
Announcements Assignment 2 and Lab 4 due Wednesday.
Presentation transcript:

Sahar Mosleh California State University San MarcosPage 1 Classes and Objects and Methods

Sahar Mosleh California State University San MarcosPage 2 Class Fundamentals A class is a template that defines the form of an object It includes both the attributes (data) and a set of methods (routines and code) that operate on the data Methods and attributes that constitute a class are called members A class specification is used to construct objects. Objects are instances of a class You may think of a class as a type, and object as variables instantiated with a specific type (class)

Sahar Mosleh California State University San MarcosPage 3 The general form of a class is: class className { type var1; type var2; … type varN; // type method1 (parameters) { Body of the method }. … type methodN (parameters) { Body of the method }

Sahar Mosleh California State University San MarcosPage 4 So far the only type of class we have seen is the one that contains main() routine Note that, the general form of a class does not specify a main() method A main() method is required only if that class is the starting point for your program Eventually, when you learn about APPLETS in Java, you will notice that applets is Java do not require main() routine

Sahar Mosleh California State University San MarcosPage 5 Consider the following example: class Vehicle { int passenger; // number of passengers int fuelcap// Fuel capacity in gallons int mpg; // fuel consumption in miles per gallon } This is an example of a simple class. The above class definition creates a new data type but nothing is allocated in memory yet. So, the class declaration is only a type description, it does not create an actual object

Sahar Mosleh California State University San MarcosPage 6 Creating Objects To create a vehicle object, you will use a statement like the following: Vehicle minivan = new Vehicle(); At this stage, minivan will be an instance of vehicle and has location in the memory; Each object that is instantiated from the vehicle class has its own copy of data members (passengers, fuelcap, mpg)

Sahar Mosleh California State University San MarcosPage 7 Accessing Data Members The general form of accessing a member of an object is object.member For example, to set the fuelcap of minivan to 16 we do: minivan.fuelcap = 16; In general you can use the dot operator to access both instance variables and methods. We will talk about methods shortly.

Sahar Mosleh California State University San MarcosPage 8 Consider the following example: class VehicleDemo {public static void main(String args[]) { Vehicle minivan = new Vehicle(); int range; minivan.passengers = 7; minivan.fuelcap = 16; minivan.mpg = 21; range = minivan.fuelcap * minivan.mpg; System.out.println(“Minivan can carry ” + minivan.passengers + “ with a range of ” + range); }  class Vehicle {int passengers; int fuelcap; int mpg; }

Sahar Mosleh California State University San MarcosPage 9 Some points to remember about this example First, you should call this file VehicleDemo.java because the main() routine is in the VehicleDemo class and not in Vehicle class After you compile this program, you will notice that you have two names with extension class in your directory. They are: Vehicle.classand VehicleDemo.class Although in this example both classes, Vehicle and VehicleDemo are in the same source file, it does not have to be this way. You may place these two classes in two separate source files. If you compile VehicleDemo.java, the other class will automatically be complied

Sahar Mosleh California State University San MarcosPage 10 How objects are created Remember that we mentioned, in order to create an object of type Vehicle, we do the following: Vehicle minivan = new Vehicle(); This declaration does two things at the same time: It declares a variable called minivan of class type Vehicle Second, the new operator creates a physical copy of object and assign a reference to that object. The above two steps can be written for the minivan object as follows: Step1 :Vehicle minivan; Step2:minivan = new Vehicle(); In step one, the value of minivan is assigned NULL automatically by Java

Sahar Mosleh California State University San MarcosPage 11 Reference Variables and Assignments In an assignment operation, object reference variables act differently than the variables of a simple type such as int. For example, int x, y; x = 5; y = x; In this case, x and y refer to different locations in memory but their contents (values) are the same. Thus, if we change x to 6 y still remains 5. Now consider, Vehiclecar1 = new Vehicle; Vehiclecar 2 = car1; In this case, both car1 and car2 refer to the same memory location. If the fuelcap attribute of car1 changes, the fuelcap of car2 has changed and vice versa.

Sahar Mosleh California State University San MarcosPage 12 Methods So far the classes we have introduced did not contain methods (except the main routine, main()) Methods are routines with a set of operations that change the state (values) of the attributes (data members) The general form of a method is: returnType methodName(parameter list) { // body of the method } Where the return type is the type returned from the method. methodName is the name of the routine (method) and parameterList is a sequence of types and identifiers separated by commas

Sahar Mosleh California State University San MarcosPage 13 Adding method to our Vehicle class class Vehicle { int passengers; int fuelcap; int mpg; void range() { System.out.println(“Range is ” + fuelcap*mpg);} } // class AddMeth {public static void main(String args[]) { Vehicle minivan = new Vehicle(); Vehicle sportscar = new Vehicle(); int range1, range2; minivan.passengers = 7; sportscar.passengers = 2; minivan.fuelcap = 16; sportscar.fuelcap = 14; minivan.mpg = 21; sportscar.mpg = 12; System.out.println(“Minivan can carry ”+minivan.passengers + “. ”); minivan.range(); System.out.println(“Sportscar carry ” + sportscar.passengers + “. ”); sportscar.range(); }

Sahar Mosleh California State University San MarcosPage 14 In the previous example, the first line of range() is void range() That declares a method called range(). This method has no parameters and return type void (i.e. nothing is returned) The body of the range method is: System.out.println(“Range is: ” + fuelcap*mpg) The range method ends when its closing brace is encountered. This causes the control to be transferred back to the caller of the function

Sahar Mosleh California State University San MarcosPage 15 In the example, the range method is called as follows: minivan.range() This calls the range method on minivan object The call to minivan.range() displays the range of vehicle defined by minivan. Similarly, sportscar.range() displays the range of vehicle defined by sportscar So each time range() is called, it displays the range for specific objects But, note that the data fuelcap, and mpg in the range() method are called directly (i.e. without using the dot (.) operator and object name). Why? The answer is, a method is always invoked relative to some object of its class. Once this invocation has occurred, the object in known. There is no reason to specify the object name again.

Sahar Mosleh California State University San MarcosPage 16 Returning a Method A method terminates under two conditions: if it completes and closing brace } is encountered if “return” statement is executed somewhere in the middle of the method If the return type of a method is void, simple return statement: return; returns the method to the caller Otherwise for the none-void methods return statements returns a value to the caller: return value;

Sahar Mosleh California State University San MarcosPage 17 Example of void method void myMeth( ) { int i; for (i=0; i<10; i++) { if (i==5) return; System.out.println(); } This is an example of a void method. The method does not return any value at all. It only prints something and terminates When the value of “i” becomes 5, the loop terminates and the control goes back to the caller of the method

Sahar Mosleh California State University San MarcosPage 18 class Vehicle { int passengers; int fuelcap; int mpg; int range() { return (fuelcap*mpg); } // class RetMeth {public static void main (String args[]) { Vehicle minivan = new Vehicle(); Vehicle sportscar = new Vehicle(); int range1, range2; minivan.passengers = 7; sportscar.passengers = 2; minivan.fuelcap = 16; sportscar.fuelcap = 14; minivan.mpg = 21; sportscar.mpg = 12; range1 = minivan.range(); range2 = sportscar.range(); System.out.println(“Minivan can carry ”+minivan.passengers + “ with range of.” + range1 + “ Miles”); System.out.println(“Sportscar can carry ” + sportscar.passengers + “with range of ” + range2 + “ Miles”); }

Sahar Mosleh California State University San MarcosPage 19 In the previous example, notice that range() has a return type of int. It means, it returns an integer value to the caller The type of the data returned by a method must be compatible with the return type specified by the method When a particular non-void function is called, the result of the function can be used in three ways: It can be stored. For example: int result = minivan.range(); It can be printed directly. For example, System.out.println(“The range is ” + minivan.range()); It can be used in an expression: int y, x, z y = x +z + minivan.range(); Or if (minivan.range() > 50) ….