Presentation is loading. Please wait.

Presentation is loading. Please wait.

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Similar presentations


Presentation on theme: "Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia."— Presentation transcript:

1 Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by Pearson Education / Addison-Wesley. Copyright © 2007 Pearson Addison-Wesley Copyright © 2008-2013 Aiman Hanna All rights reserved

2 Class Definitions You have already been using some of the predefined classes, i.e. String and Scanner classes You have already been using some of the predefined classes, i.e. String and Scanner classes You can add/define your own classes to the language You can add/define your own classes to the language A class determines: A class determines: 1) Attributes, or Instance Variables: the types of data that an object can contain, 1) Attributes, or Instance Variables: the types of data that an object can contain, 2) Methods: the actions it can perform 2) Methods: the actions it can perform Once a new class is defined, objects, or instances, can be created from this class Once a new class is defined, objects, or instances, can be created from this class 4-2

3 Class Definitions 4-3 int x, y; char ch; Data declarations Method declarations

4 The new Operator An object of a class is named or declared by a variable of the class type: An object of a class is named or declared by a variable of the class type: ClassName objectName; ClassName objectName; The new operator must then be used to create the object and associate it with its variable name (however, some few exceptions do exist): The new operator must then be used to create the object and associate it with its variable name (however, some few exceptions do exist): objectName = new ClassName(); objectName = new ClassName(); These can be combined as follows: These can be combined as follows: ClassName objectName = new ClassName(); ClassName objectName = new ClassName();Example: Car c1 = new Car(); // Car is the class name and // c1 is the object name // c1 is the object name 4-4

5 Instance Variables and Methods Instance variables (attributes) can be defined as in the following two examples Instance variables (attributes) can be defined as in the following two examples Note the public modifier (for now): Note the public modifier (for now): public int numberOfDoors; public int numberOfDoors; public double Price; public double Price; In order to refer to a particular instance variable, preface it with its object name as follows: In order to refer to a particular instance variable, preface it with its object name as follows:c1.pricec2.pricec1.numberOfDoors C1 & c2 are just two objects from the class 4-5

6 Method definitions are divided into two parts: a heading and a method body: Method definitions are divided into two parts: a heading and a method body: public void myMethod() // Heading public void myMethod() // Heading { code to perform some action // Body code to perform some action // Body and/or compute a value and/or compute a value } Methods are invoked using the name of the calling object and the method name as follows: Methods are invoked using the name of the calling object and the method name as follows: objName.methodName(); objName.methodName();Example:C1.getNumberOfDoors(); Invoking a method is equivalent to executing the method body Invoking a method is equivalent to executing the method body Instance Variables and Methods 4-6

7 File Names and Locations Reminder: a Java file must be given the same name as the class it contains with an added.java at the end Reminder: a Java file must be given the same name as the class it contains with an added.java at the end For example, a class named Car must be in a file named Car.java For example, a class named Car must be in a file named Car.java For now, your program and all the classes it uses should be in the same directory or folder For now, your program and all the classes it uses should be in the same directory or folder 4-7

8 More About Methods There are two kinds of methods: There are two kinds of methods: Methods that compute/perform an action then return a value Methods that compute/perform an action then return a value Methods that compute/perform an action then does not return a value Methods that compute/perform an action then does not return a value This type of method is called a void method; in other words, it returns void This type of method is called a void method; in other words, it returns void Notice that in both cases, the function do indeed perform an action Notice that in both cases, the function do indeed perform an action 4-8 Copyright © 2007 Pearson Addison-Wesley. Copyright © 2007 Aiman Hanna. All rights reserved.

9 More About Methods A method that returns a value must specify the type of that value in its heading: A method that returns a value must specify the type of that value in its heading: public typeReturned methodName(paramList) public typeReturned methodName(paramList) Note: paramList is optional Examples: public double getPrice(); public int getNumOfDoors(); public void setNumOfDoors(int nd); // nd is just // a name // a name 4-9

10 main is a void Method A program in Java is just a class that has a main method A program in Java is just a class that has a main method When you give a command to run a Java program, the run-time system invokes the method main When you give a command to run a Java program, the run-time system invokes the method main Note that main is a void method, as indicated by its heading: Note that main is a void method, as indicated by its heading: public static void main(String[] args) 4-10

11 return Statements The body of both types of methods contains a list of declarations and statements enclosed in a pair of braces The body of both types of methods contains a list of declarations and statements enclosed in a pair of braces public myMethod() public myMethod() { declarations Body declarations Body statements statements } 4-11

12 return Statements The body of a method that returns a value must also contain one or more return statements The body of a method that returns a value must also contain one or more return statements A return statement specifies the value returned and ends the method invocation: A return statement specifies the value returned and ends the method invocation: return Expression; return Expression; Expression can be any expression that evaluates to something of the type returned listed in the method heading Expression can be any expression that evaluates to something of the type returned listed in the method heading 4-12

13 return Statements A void method need not contain a return statement, unless there is a situation that requires the method to end before all its code is executed A void method need not contain a return statement, unless there is a situation that requires the method to end before all its code is executed In this context, since it does not return a value, a return statement is used without an expression: In this context, since it does not return a value, a return statement is used without an expression: return; return; 4-13

14 Method Definitions An invocation of a method that returns a value can be used as an expression anyplace that a value of the returned type can be used: An invocation of a method that returns a value can be used as an expression anyplace that a value of the returned type can be used: double pr; pr = c1.getPrice(); An invocation of a void method is simply a statement: An invocation of a void method is simply a statement:objectName.methodName();Examples:c1.setPrice(20000);c1.showModel(); 4-14 VehicleSearch1.java (MS-Word file) VehicleSearch1.java (MS-Word file) VehicleSearch1.javaMS-Word file VehicleSearch1.javaMS-Word file

15 Example: The Vehicle Class 4-15 See VehicleSearch1.java See VehicleSearch1.java VehicleSearch1.java v1, v2 & v3 upon creation int numOfDoors; double price; int maxSpeed; class Vehicle numOfDoors 4 price 10000 maxSpeed 280 numOfDoors 4 v2 price 10000 maxSpeed 280 numOfDoors 4 v3 price 10000 maxSpeed 280 v1

16 Constructors A constructor is a special kind of method that is designed to initialize the instance variables for an object: A constructor is a special kind of method that is designed to initialize the instance variables for an object: public ClassName(anyParameters){code} A constructor must have the same name as the class A constructor must have the same name as the class A constructor has no type returned, not even void A constructor has no type returned, not even void 4-16 VehicleSearch2.java (MS-Word file) VehicleSearch2.java (MS-Word file) VehicleSearch2.javaMS-Word file VehicleSearch2.javaMS-Word file

17 public and private Modifiers The modifier public means that there are no restrictions on where an instance variable or method can be used The modifier public means that there are no restrictions on where an instance variable or method can be used The modifier private means that an instance variable or method cannot be accessed by name outside of the class The modifier private means that an instance variable or method cannot be accessed by name outside of the class 4-17 VehicleSearch4.java (MS-Word file) VehicleSearch4.java (MS-Word file) VehicleSearch4.javaMS-Word file VehicleSearch4.javaMS-Word file VehicleSearch3.java (MS-Word file) VehicleSearch3.java (MS-Word file) VehicleSearch3.javaMS-Word file VehicleSearch3.javaMS-Word file

18 Include a No-Argument Constructor You should include a default, or no-argument constructor as part of your program. Default constructors will be discussed later in full details. You should include a default, or no-argument constructor as part of your program. Default constructors will be discussed later in full details. If you do not include any constructors in your class, Java will automatically create a default or no-argument constructor that takes no arguments, performs no initializations, but allows the object to be created If you do not include any constructors in your class, Java will automatically create a default or no-argument constructor that takes no arguments, performs no initializations, but allows the object to be created If you include even one constructor (possibly non-default) in your class, Java will not provide this default constructor If you include even one constructor (possibly non-default) in your class, Java will not provide this default constructor 4-18

19 Local Variables A variable declared within a method definition is called a local variable A variable declared within a method definition is called a local variable All variables declared in the main method are local variables All variables declared in the main method are local variables All method parameters are local variables All method parameters are local variables If two methods each have a local variable of the same name, they are still two entirely different variables If two methods each have a local variable of the same name, they are still two entirely different variables 4-19

20 Global Variables Some programming languages include another kind of variable called a global variable Some programming languages include another kind of variable called a global variable The Java language does not have global variables The Java language does not have global variables 4-20

21 Blocks A block is another name for a compound statement, that is, a set of Java statements enclosed in braces, {} A block is another name for a compound statement, that is, a set of Java statements enclosed in braces, {} A variable declared within a block is local to that block, and cannot be used outside the block A variable declared within a block is local to that block, and cannot be used outside the block Once a variable has been declared within a block, its name cannot be used for anything else within the same method definition Once a variable has been declared within a block, its name cannot be used for anything else within the same method definition 4-21

22 Declaring Variables in a for Statement You can declare one or more variables within the initialization portion of a for statement You can declare one or more variables within the initialization portion of a for statement A variable so declared will be local to the for loop, and cannot be used outside of the loop A variable so declared will be local to the for loop, and cannot be used outside of the loop If you need to use such a variable outside of a loop, then declare it outside the loop If you need to use such a variable outside of a loop, then declare it outside the loop 4-22 Statements15.java (MS-Word file) Statements15.java (MS-Word file) Statements15.javaMS-Word file Statements15.javaMS-Word file Statements14.java (MS-Word file) Statements14.java (MS-Word file) Statements14.javaMS-Word file Statements14.javaMS-Word file

23 Parameters of a Primitive Type A method can accept no parameters, one parameter, or few of them (parameter list) A method can accept no parameters, one parameter, or few of them (parameter list) These parameter(s) are referred to as formal parameters These parameter(s) are referred to as formal parameters public void setVehicleInfo(int nd, double pr, int mxsp) When a method is invoked, the appropriate values must be passed to the method in the form of arguments, and must be in the right order When a method is invoked, the appropriate values must be passed to the method in the form of arguments, and must be in the right order These arguments are called actual parameters These arguments are called actual parameters c1.setVehicleInfo(4, 12500.99, 280); 4-23

24 Parameters of a Primitive Type The type of each argument must be compatible with the type of the corresponding parameter. The following two statements use the method correctl The type of each argument must be compatible with the type of the corresponding parameter. The following two statements use the method correctl c1.setVehicleInfo(4, 12500.99, 280); int n = 5, m = 260; double p = 19700.95; c1.setVehicleInfo(n, p, m); NOTE: In both examples, the value of each argument (not the variable name) is the one plugged into the corresponding method parameter NOTE: In both examples, the value of each argument (not the variable name) is the one plugged into the corresponding method parameter This method of plugging in arguments for formal parameters is known as the call-by-value mechanism This method of plugging in arguments for formal parameters is known as the call-by-value mechanism 4-24 MethodParameters1.java (MS-Word file) MethodParameters1.java (MS-Word file) MethodParameters1.javaMS-Word file MethodParameters1.javaMS-Word file

25 Parameters of a Primitive Type If argument and parameter types do not match exactly, Java will attempt to make an automatic type conversion If argument and parameter types do not match exactly, Java will attempt to make an automatic type conversion A primitive argument can be automatically type cast from any of the following types, to any of the types that appear to its right: A primitive argument can be automatically type cast from any of the following types, to any of the types that appear to its right: byte  short  int  long  float  double byte  short  int  long  float  double char char 4-25

26 Methods That Return a Boolean Value An invocation of a method that returns a value of type boolean returns either true or false An invocation of a method that returns a value of type boolean returns either true or false Therefore, it is common practice to use an invocation of such a method to control statements and loops where a Boolean expression is expected Therefore, it is common practice to use an invocation of such a method to control statements and loops where a Boolean expression is expected if-else statements, while loops, etc. if-else statements, while loops, etc. 4-26

27 Comparing Objects of the Same Class for Equality You cannot use == to compare objects You cannot use == to compare objects 4-27 VehicleCompare1.java (MS-Word file) VehicleCompare1.java (MS-Word file) VehicleCompare1.javaMS-Word file VehicleCompare1.javaMS-Word file Instead use methods such as user-defined equals, or toString to compare the objects Instead use methods such as user-defined equals, or toString to compare the objects VehicleCompare2.java (MS-Word file) VehicleCompare2.java (MS-Word file) VehicleCompare2.javaMS-Word file VehicleCompare2.javaMS-Word file VehicleCompare3.java (MS-Word file) VehicleCompare3.java (MS-Word file) VehicleCompare3.javaMS-Word file VehicleCompare3.javaMS-Word file VehicleCompare4.java (MS-Word file) VehicleCompare4.java (MS-Word file) VehicleCompare4.javaMS-Word file VehicleCompare4.javaMS-Word file

28 Accessor and Mutator Methods Accessor methods allow the programmer to obtain the value of an object's instance variables Accessor methods allow the programmer to obtain the value of an object's instance variables The data can be accessed but not changed The data can be accessed but not changed The name of an accessor method typically starts with the word get The name of an accessor method typically starts with the word get Mutator methods allow the programmer to change the value of an object's instance variables in a controlled manner Mutator methods allow the programmer to change the value of an object's instance variables in a controlled manner Incoming data is typically tested and/or filtered Incoming data is typically tested and/or filtered The name of a mutator method typically starts with the word set The name of a mutator method typically starts with the word set 4-28

29 Encapsulation 4-29

30 A Class Has Access to Private Members of All Objects of the Class Within the definition of a class, private members of any object of the class can be accessed, not just private members of the calling object Within the definition of a class, private members of any object of the class can be accessed, not just private members of the calling object For example, see the equals function in VehicleCompare2.java For example, see the equals function in VehicleCompare2.java VehicleCompare2.java The function has access to the private date of the passed object, vec 4-30


Download ppt "Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia."

Similar presentations


Ads by Google