More Object Concepts— Farrell, Chapter 4 Dr. Burns.

Slides:



Advertisements
Similar presentations
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
1 Chapter Three Using Methods. 2 Objectives Learn how to write methods with no arguments and no return value Learn about implementation hiding and how.
Road Map Introduction to object oriented programming. Classes
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Applying OO Concepts Using Java. In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Java Programming, Second Edition Chapter Four Advanced Object Concepts.
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Chapter 8 More Object Concepts
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
More Object Concepts Chapter 4.  Our class is made up of several students and each student has a name and test grades  How do we assign the variables.
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.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
1 Java Programming Using Methods, Classes, and Objects.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo CET 3640 © Copyright by Pearson Education, Inc. All Rights Reserved.
Session 7 Methods Strings Constructors this Inheritance.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Object Oriented Programming with Java 03 - Introduction to Classes and Objects.
1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
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,
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Topics Instance variables, set and get methods Encapsulation
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Methods, classes, and Objects Dr. Jim Burns. Question  Which of the following access modifiers is the default modifier?  public  private  protected.
Methods. Methods are groups of statements placed together under a single name. All Java applications have a class which includes a main method class MyClass.
More About Objects and Methods
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Functions II
Objects and Classes.
Chapter 3: Using Methods, Classes, and Objects
Chapter 6 Methods: A Deeper Look
Object Based Programming
Chapter 6 Methods: A Deeper Look
Object-Oriented Programming Using C++ Second Edition
CHAPTER 6 GENERAL-PURPOSE METHODS
Object Oriented Programming in java
More About Objects and Methods
Applying OO Concepts Using Java
Classes, Objects and Methods
Presentation transcript:

More Object Concepts— Farrell, Chapter 4 Dr. Burns

Outline Blocks and Scope Blocks and Scope Overload a Method Overload a Method Ambiguity Ambiguity Send arguments to constructors Send arguments to constructors Overload constructors Overload constructors This This Static variables Static variables Constants Constants Automatically imported, prewritten constants and methods Automatically imported, prewritten constants and methods Explicitly imported prewritten class Explicitly imported prewritten class

Blocks and Scope Public static void methodWithNestedBlocks() { int aNumber = 10; // aNumber comes into existence int aNumber = 10; // aNumber comes into existence Ssytem.out.println(“In outer block, ANumber is “ + aNumber); { int anotherNumber = 512; // anotherNumber comes into existence system.out.println(“In inner block, aNumber is “ + aNumber + “ and another number is “ + anotherNumber); } // anotherNumber ceases to exist System.out.println(“In outer block, aNumber is “ + aNumber); } // aNumber ceases to exist

Blocks and Scope Blocks must be completely nested within other blocks A local variable declared within an outer block remains in scope anywhere within that block A local variable declared within an inner block falls out of scope when control passes from that block and the variable ceases to exist

Still more blocks and scope Do not attempt to re-declare a local variable within an inner block, because that variable is still active You cannot declare a variable more than once in a block You can use the same variable name within two blocks that are not nested—they occupy different locations in memory

Local variables…. Always mask or hide other variables in a class that have the same name Always mask or hide other variables in a class that have the same name

Question An instance of a class gets created at the point where the keyword new appears An instance of a class gets created at the point where the keyword new appears Where does the instance get destroyed? Where does the instance get destroyed? If you exit a method that creates an object and later return to that method, will that instance still be there? If you exit a method that creates an object and later return to that method, will that instance still be there?

Overload a Method Overloading a method means using the same method name but with different args and different definitions/declarations as well Overloading a method means using the same method name but with different args and different definitions/declarations as well When you overload a Java method, you write multiple methods with the same name When you overload a Java method, you write multiple methods with the same name

public static void calculateInterest(double bal, double rate) { Double interest; Interest = bal * rate; System.out.println(“Simple interest on $” + bal + “ at “ + rate + “% rate is “ + interest); }

Ambiguity When an application contains just one version of a method, you can call the method using a parameter of the correct data type, on one that can be promoted to the correct data type. When an application contains just one version of a method, you can call the method using a parameter of the correct data type, on one that can be promoted to the correct data type. For example, assume a method has a single argument that has been declared to be double. If, instead, an int is passed to the method, the int is cast as (promoted to) a double and there is no compiler error. For example, assume a method has a single argument that has been declared to be double. If, instead, an int is passed to the method, the int is cast as (promoted to) a double and there is no compiler error.

More Ambiguity If a second method exists that will accept an int parameter, the compiler will use the second method rather than casting the int to a double and using the first method. If a second method exists that will accept an int parameter, the compiler will use the second method rather than casting the int to a double and using the first method. This is called overloading of methods or method overloading This is called overloading of methods or method overloading

More Ambiguity Consider two methods with two arguments. In the first method the arguments are int and double; in the second method the arguments are double and int If you call this method with two int parameters, an ambiguous situation arises because there is not exact match for the method call. Consider two methods with two arguments. In the first method the arguments are int and double; in the second method the arguments are double and int If you call this method with two int parameters, an ambiguous situation arises because there is not exact match for the method call.

More ambiguity The compiler could promote the second int to a double and call the first method or promote the first int to a double and call the second method The compiler could promote the second int to a double and call the first method or promote the first int to a double and call the second method This will not run problem-free This will not run problem-free

Send arguments to constructors Recall that Java automatically provides a constructor method when you crease a class. You can, however, provide your own constructor method if you’d like to initialize your fields to something other than the default initializations. Recall that Java automatically provides a constructor method when you crease a class. You can, however, provide your own constructor method if you’d like to initialize your fields to something other than the default initializations.

When you write your own constructor… You can provide for arguments or parameters that are often used to pass initialization values You can provide for arguments or parameters that are often used to pass initialization values Suppose that full-time employees have a field called empNum that is initialized to 999, but part-time employees have an empNum that is initialized to 888 Suppose that full-time employees have a field called empNum that is initialized to 999, but part-time employees have an empNum that is initialized to 888

Example Public class Employee { Private int empNum; Employee(int num) { empNum = num; }} Employee fullTimeWorker = new Employee(999) Employee partTimeWorker = new Employee(888)

Overload constructors This is just several different constructors with different arguments types in each This is just several different constructors with different arguments types in each Analogous to overload methods Analogous to overload methods Two use this capability, you have to explicitly define at least how many constructors? Two use this capability, you have to explicitly define at least how many constructors?

One constructor with args, a second with none public class Employee { private int empNum; Employee(int num) { empNum = num; }Employee(){ empNum = 999; }}

this When you create 200 instantiations of a class, you get 200 instantiations of the data fields (variables) in the class When you create 200 instantiations of a class, you get 200 instantiations of the data fields (variables) in the class Do you get 200 instantiations of the methods in the class??? Do you get 200 instantiations of the methods in the class??? Only the class itself maintains the methods Only the class itself maintains the methods

More of this Suppose you need the empNum of employee worker--the code is Suppose you need the empNum of employee worker--the code is Int employeeNumber = aWorker.getempNum(); This uses the employee class getempNum() method and it gets the employee number from the instance aWorker The compiler figures out whose employee number is to retrieved by the single method getempNum()

Still more of this You implicitly passed a reference (address) to the employee getempNum() method by use of the aWorker You implicitly passed a reference (address) to the employee getempNum() method by use of the aWorker The method actually implements code that looks as follows: The method actually implements code that looks as follows:

The getEmpNum() Code Public int getEmpNum() { return this.empNum; } However, usually you don’t have to explicitly use the this keyword

So the code can look like Public int getEmpNum() { return empNum; }

public class Student { private int stuNum; private double gpa; Public Student(int stuNum, double gpa) { stuNum = stuNum; gpa = gpa; } Public void showStudent() { System.out.printlin(“Student #” + stuNum + “ gpa is “ + gpa); }}

Public class TestStudent { public static void main(String[] args) { Student a PsychMajor = new Student(111,3.5); aPsychMajor.showStudent();}}

The result here is… Student #0 gpa is 0.0 Student #0 gpa is 0.0 Not what we wanted… Not what we wanted… The compiler treats The compiler treats stuNum = stuNum; gpa = gpa; As local variable = local variable

public class Student { private int stuNum; private double gpa; Public Student(int stuNum, double gpa) { this.stuNum = stuNum; this.gpa = gpa; } Public void showStudent() { System.out.println(“Student #” + stuNum + “ gpa is “ + gpa); }}

The result here is… Student #111 gpa is 3.5 Student #111 gpa is 3.5 Here, the use of this must be explicit, because the use of this causes the compiler to understand class variable = local variable Which is what we want

static variables are class variables Class methods have no objects associated with them and cannot use a this reference; they are declared static Class methods have no objects associated with them and cannot use a this reference; they are declared static Class methods, such as main are static, they can not be used in conjunction with instance objects Class methods, such as main are static, they can not be used in conjunction with instance objects Conversely, we should not declare methods of classes that will be instantiated as static Conversely, we should not declare methods of classes that will be instantiated as static

class variables Are shared, common to every instance of a class Are shared, common to every instance of a class Instance variables are separate for every instance of a class Instance variables are separate for every instance of a class

Public class BaseballPlayer { private static int count = 0; private int number; private double batttingAverage; public BaseballPlayer(ind id, double avg) { number = id; battingAverage = avg; count = count + 1; } Public void showPlayer() { System.out.println(“Player #” + number + “ batting average is “ + battingAverage + “ There are “ + coundt + “ players”); }}

Public class TestPlayer { public static void main(String[] args) { Baseballplayer aCatcher = new BaseballPlayer(12,.2218); BaseballPlayer aShortstop = new BaseballPlalyer(31,.385); aCatcher.showPlayer();aShortstop.showplayer(); BaseballPlayer anOutfielder = new BaseballPlalyer(44,.505); anOutfielder.showPlayer();aCatcher.showPlayer();}}

OUTPUT Player #12 batting average is.218 There are 2 players Player #31 batting average is.385 There are 2 players Player #44 batting average is.505 There are 3 players Player #12 batting average is.218 There are 3 players

Constants Literal strings are constants, like “First Java Application” Literal strings are constants, like “First Java Application” So are numbers, like So are numbers, like These are literal constants These are literal constants Variables, on the other hand, do change Variables, on the other hand, do change

Public class Student { private static final int SCHOOL_ID = 12345; private int stuNum; private double gpa; public Student(int stuNum, double gpa) { this.stuNum = stuNum; this.gpa = gpa; } public void showStudent () { System.out.println(“Student #” + stuNum + “ gpa is “ + gpa); }}

Notice the reserved word final final indicates that a field value is permanent. final indicates that a field value is permanent. The identifier SCHOOL_ID is a symbolic constant The identifier SCHOOL_ID is a symbolic constant For such it is customary to use all caps and to include underscores between words For such it is customary to use all caps and to include underscores between words This helps us distinguish symbolic constants from variables This helps us distinguish symbolic constants from variables

Symbolic constants You cannot change the value of a symbolic constant after declaring it You cannot change the value of a symbolic constant after declaring it You must initialize a constant with a value You must initialize a constant with a value If a declared constant does not receive a value at the time of its creation, it can never receive a value If a declared constant does not receive a value at the time of its creation, it can never receive a value Using symbolic constants makes your programs easier to understand, as opposed to using the literal value Using symbolic constants makes your programs easier to understand, as opposed to using the literal value

Automatically imported, prewritten constants and methods There are over 500 pre-written classes that you can avail yourself of There are over 500 pre-written classes that you can avail yourself of Re-use is the way to get time and cost leverage in creating ‘new’ applications Re-use is the way to get time and cost leverage in creating ‘new’ applications You have already used the System and JOptionPane classes You have already used the System and JOptionPane classes Each of these is stored in a package or library of classes—a folder that provides a convenient grouping for classes. Each of these is stored in a package or library of classes—a folder that provides a convenient grouping for classes.

Importing packages When you used the JOptionPane class you had to import the java.swing package into your program with the statement.. When you used the JOptionPane class you had to import the java.swing package into your program with the statement.. Import javax.swing.JOptionPane; Import javax.swing.JOptionPane; The class System does not have to be imported The class System does not have to be imported

Math functions Are available in the package java.lang.Math Are available in the package java.lang.Math Do not have to be imported Do not have to be imported All constants and methods in this package are static—therefore, they are All constants and methods in this package are static—therefore, they are Class variables Class variables Class methods Class methods

Examples of use.. areaOfCircle = java.lang.Math.Pi * radius * radius; areaOfCircle = java.lang.Math.Pi * radius * radius; Or simply… Or simply… areaOfCircle = Math.PI * radius * radius; areaOfCircle = Math.PI * radius * radius; Where Where Public final static double PI = ; Public final static double PI = ;

Explicitly imported prewritten classes and their methods Only a few prewritten classes are included in the programs you write, like those in the System class and those in the java.lang class Only a few prewritten classes are included in the programs you write, like those in the System class and those in the java.lang class The rest have to be imported, like The rest have to be imported, like Import javax.swing.JOptionPane; Import javax.swing.JOptionPane; You can either import the entire class or import the package in which the class is contained You can either import the entire class or import the package in which the class is contained

There are three ways to access pre-written classes that are not included automatically 1. Use the entire path with the class name 2. Import the class 3. Import the package that contains the class you are using

Consider the java.util class containing the class GregorianCalendar You can instantiate an object of type GregorianClaenday from this class by using the full class path, as in You can instantiate an object of type GregorianClaenday from this class by using the full class path, as in Java.util.GregorianCalendar myAnniversary = new java.util.GregorianCalendar();

Alternatively… You can include an important statement like You can include an important statement like Import java.util.GregorianCalendar; Then the declaration of the instance is gregorianCalendar myAnniversary = new GregorianCalendar();

Import statements must appear where?? Before the first executable statement of your java class file Before the first executable statement of your java class file

As an alternative to importing a class you can import an entire package of classes Instead of… Instead of… Import java.util.GregorianCalendar; You can use Import java.util.*; imports all of the Java.util classes, not just the GregorianCalendar class Here you are use the * as a wildcard symbol

// AGE CALCULATOR import java.util.*; import javax.swing.*; public class AgeCalculator { public static void main(String[] args) public static void main(String[] args) { GregorianCalendar now = new GregorianCalendar(); GregorianCalendar now = new GregorianCalendar(); int nowYear; int nowYear; int birthYear; int birthYear; int yearsOld; int yearsOld; birthYear = Integer.parseInt(JOptionPane.showInputDialog(null, "In what year were you born?")); birthYear = Integer.parseInt(JOptionPane.showInputDialog(null, "In what year were you born?")); nowYear = now.get(Calendar.YEAR); nowYear = now.get(Calendar.YEAR); yearsOld = nowYear - birthYear; yearsOld = nowYear - birthYear; JOptionPane.showMessageDialog(null, JOptionPane.showMessageDialog(null, "This is the year you become " + yearsOld + " years old"); "This is the year you become " + yearsOld + " years old"); System.exit(0); System.exit(0); }}