Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.

Slides:



Advertisements
Similar presentations
Lecture 3: Topics If-then-else Operator precedence While loops Static methods Recursion.
Advertisements

Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
Java: How to Program Methods Summary Yingcai Xiao.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Lecture From Chapter 6 & /8/10 1 Method of Classes.
Encapsulation CMSC 202. Types of Programmers Class programmers – Developers of new classes – Goal: Expose the minimum interface necessary to use a new.
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.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing 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.
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.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
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.
Constructors & Garbage Collection Ch. 9 – Head First Java.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Object-Oriented Design Chapter 7 1. Objectives You will be able to Use the this reference in a Java program. Use the static modifier for member variables.
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.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Defining Your Own Classes II
Functions + Overloading + Scope
Topic: Classes and Objects
Lecture 7 D&D Chapter 7 & 8 Composite Classes and enums Date.
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
4. Java language basics: Function
Lecture 14 Throwing Custom Exceptions
Templates.
Examples of Classes & Objects
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Lecture 5 D&D Chapter 6 Arrays and ArrayLists Date.
Methods Chapter 6.
ADT’s, Collections/Generics and Iterators
CompSci 230 S Programming Techniques
Lecture 10: More on Methods and Scope
Object Oriented Systems Lecture 03 Method
Methods.
Lecture 11 B Methods and Data Passing
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Chapter 9 Inheritance and Polymorphism
Phil Tayco Slide version 1.0 Created Oct 2, 2017
Lecture 11 C Parameters Richard Gesick.
Corresponds with Chapter 7
Chapter 6 Methods: A Deeper Look
CHAPTER 6 GENERAL-PURPOSE METHODS
Java Classes and Objects 3rd Lecture
Java Programming Function Introduction
CS2011 Introduction to Programming I Methods (II)
Chapter 4 Topics: class declarations method declarations
Chapter 6 Methods.
Methods and Data Passing
Workshop for Programming And Systems Management Teachers
Objects and Classes Creating Objects and Object Reference Variables
CSCI 3328 Object Oriented Programming in C# Chapter 6: Methods
6 Methods: A Deeper Look.
Method of Classes Chapter 7, page 155 Lecture /4/6.
Classes, Objects and Methods
Chapter 6 Objects and Classes
Java Programming Function Introduction
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Loops and Iteration CS 21a: Introduction to Computing I
Visibilities and Static-ness
Corresponds with Chapter 5
Methods and Data Passing
Presentation transcript:

Lecture 4 D&D Chapter 5 Methods including scope and overloading Date

Goals By the end of this lesson, you should know how to write a method and call it know how to write an overloaded method and call it. know how to call a Java API static or non-static method understand the difference between static and non-static methods understand the basics of scope

Calling Java Methods Method calls Declarations Static and non-static methods Scope and call stack Java API Summary System.out.println( "The smallest float number from Math.min is " + Math.min(number1,Math.min(number2,number3))); System and Math are special classes that are always available and the methods are static so can be called directly without instantiating a System or Math object – this is another Java ‘cheat’. import java.util.Scanner; … Scanner input = new Scanner(System.in); double number1 = input.nextDouble(); Scanner obeys the OO rules: you have an import to explicitly include the java library you must declare and instantiate a scanner object (named input here) then you can call the .nextDouble() method

This is dictated by Java Method declarations public static void main(String[] args) { …. double result = maximum(number1,number2, number3); } public static double maximum(double x, double y, double z){ ……… return biggest; } This is dictated by Java Method calls Declarations Static and non-static methods Scope and call stack Java API Summary public can be seen by other objects/classes (alternative private or nothing) static method can be use even if the object isn’t instantiated (this is pretty ugly and not pure OO avoid wherever possible. Here the method must be static because it is being called by a static method - main() unless we instantiate the class again inside itself (recursion). double the data type the method will return maximum the method name – something you make up, first letter small. (double x,….) the parameters to be passed to the method, each typed

Method overloading Method calls Declarations double result = maximum(int1, int2, int3); We could call the maximum method, passing it integers int1, int2, and int3 instead of doubles. Java will ‘promote’ them to doubles. It will do this anytime you will not lose data (e.g., int or float to double, but not double to float or float to int). Alternatively”, we could have another method of the same name with a different signature, i.e.: public static int maximum(int x, int y, int z){… } Java will use the method with the best signature match. If you passed a mix of doubles and ints, it would use the double version because it can promote the ints to doubles but not the other way around. You could have another maximum() that takes 4 values… This is called method overloading. How many overloads does Math.min() have? Method calls Declarations Static and non-static methods Scope and call stack Java API Summary

Type casting variables int intResult = (int) maximum(int1,int2,int3); We can also explicitly change the type of something in a statement. So we could use the double maximum method and type cast the return value to an integer. Type casting can be done in almost any statement by putting the destination type before the variable in () You must to be aware that you can lose data! double doubleX = 2.8; intX = (int) double; // What will be in intX? Answer? There is of course Math.round() int intResult = Math.round(maximum(int1,int2,int3)); Method calls Declarations Static and non-static methods Scope and call stack Java API Summary

static methods Java knows two types of methods: Method calls Declarations Static and non-static methods Scope and call stack Java API Summary Java knows two types of methods: Non-static methods (sometimes also known as “object methods” or “member methods”). These are declared in the class but can only be called (invoked) on an actual instance (object) of the class. Non-static methods can work with data stored in the object. Static methods (=declared as static). Also known as “class methods”. These are also declared in the class but don’t require an actual instance of the class to be called. Because of this, static methods cannot work with data stored in objects of the class.

static methods Method calls Declarations Static and non-static methods Scope and call stack Java API Summary Non-static methods we have met: nextDouble() in Scanner objects, but we’ll soon meet more. In fact, most methods in practice are not static. Static methods we have met: main(), maximum(), Math.min()

Three types of method calls Declarations Static and non-static methods Scope and call stack Java API Summary Call a method in the same class returnVar = methodName(parameters); 2. Call a Java static method (aka “class method”): returnVar = ClassName.methodName(parameters); 3. Call a non-static method in another class import …… … ClassName objectName = new ClassName(); returnVar = objectName.method(…);

Scope Method calls Declarations Static and non-static methods Scope and call stack Java API Summary Classes, objects, methods and variables all have a scope: The scope of a class is/are the section(s) of code in which we can, e.g., declare variables to be of type of the class, instantiate objects of the class and call class methods. The scope of a method is/are the section(s) of code in which we can invoke the method. The scope of a method is/are the section(s) of code in which we can read the variable or assign it a value. Scope is governed by where something is defined and what visibility modifiers it has: public: visible to code anywhere private: visible to code inside the class only Generally, everything is in scope within the code block in which it is defined.

Scope Method calls Declarations Static and non-static methods public class Dog { public String name; public void come() { System.out.println("You called " + name + "? Rushing to you..."); } public void behave() { sleep(); chewSomething(); private void sleep() { System.out.println("Zzzzzz..."); System.out.println("Waking up..."); private void chewSomething() { System.out.println("Chewing your favourite shoe..."); Method calls Declarations Static and non-static methods Scope and call stack Java API Summary

Scope Method calls Declarations Static and non-static methods public class Scope { public static void main(String[] args) { // Can instantiate a Dog because it's a public class Dog myDog = new Dog(); myDog.name = "Patsy"; // Can call come() method on myDog object because // come() is public myDog.come(); // Can call behave() method on myDog object because // behave() is public myDog.behave(); // Can't call sleep() method on myDog object because // sleep() is private. //The following line won't compile. // myDog.sleep(); } Method calls Declarations Static and non-static methods Scope and call stack Java API Summary

myDog.ChewSomething() Stack and scope A method must know where to return control when it completes. The program builds a call stack. Think of it as a stack of plates: The most recent call (plate) is on the top – when it finishes control is passed to the next entry (plate) down. Calls are ‘pushed’ onto the top of stack and ‘popped’ off the top. Method calls Declarations Static and non-static methods Scope and call stack Java API Summary System.out.println() myDog().sleep() System.out.println() myDog.ChewSomething() myDog().behave() myDog().come() Scopes::main()

Stack and scope stack In scope variables Method calls Declarations You can see the stack and the in-scope variables in the debugger Method calls Declarations Static and non-static methods Scope and call stack Java API Summary stack In scope variables

Variables in Java Method calls Declarations Static and non-static methods Scope and call stack Java API Summary In Java, you declare variables in four contexts: Inside a method: These variables are for the method to work with and are not visible outside the method. Outside a method in a class: These variables are for the methods of the class to use and, if declared public, can be set and read by code outside the class. As normal variables (non-static). If declared outside a method, each object (instance) of the class gets its own copy of the variable. If we change the value in one instance, the copies in the other instances don’t change. As static variables. These are declared outside a method only. There is only a single copy of the variable, and we need no object instance to be able to read or write to the variable. Static and non-static methods can work with static variables.

Java API java.util Math java.awt – graphics Method calls Declarations Static and non-static methods Scope and call stack Java API Summary You may have wondered where Scanner and Math came from. Java provides you with a huge number of ready-made classes, which in turn contain many more methods, both static and non-static, and in many cases overloaded multiple times. We will see more and more examples as we go. A few you will use include: java.util Math java.awt – graphics javax.swing – gui components

What do we know Method calls Declarations Static and non-static methods Scope and call stack Java API Summary Java method calls look different depending on whether the method is in one of the special class (eg System or Math) Is static – in which case you do not need to instantiate an object Is non-static - when you do need to instantiate the object Calling your own method in the same class requires just the method name and parameters Declaring a method you include its Scope (public or private) Static if required (eg in the same class as main()) Return type Name Parameter list (type name, type name, …) Code block braces ( {} ) You can overload methods by declaring multiple methods with the same name but different signatures Different return type and/or Different parameters Java will choose the most appropriate match You can change the type of something by casting it – you may lose data if you are not careful. (type) variable

Resources Method calls Declarations Static and non-static methods Scope and call stack Java API Summary D&D chapter 5 https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html Homework Revision exercises in Chapter 5 Play with the lecture example code.

Next Lecture D&D Chapters 6 Arrays and ArrayLists