L EC. 06: C LASS D ETAILS (2/2) 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length.

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
A C LOSER L OOK AT C LASSES 1. A SSIGNING O BJECTS One object can be assigned to another provided that both objects are of the same type. It is not sufficient.
1 CLASSES. 2 Class Fundamentals It defines a new data type Once defined, this new type can be used to create objects of that type A class is a template.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Memory Management & Method Calls in Java Program Execution © Allan C. Milne v
Lecture 2 Classes and objects, Constructors, Arrays and vectors.
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
Chapter 51 Feb 08, Chapter 52  Methods in a class are invoked using objects A a1 = new A(); a1.func1();  Calling object and the dot can be omitted.
Metode di Java Risanuri Hidayat, Ir., M.Sc.. Pendahuluan Classes usually consist of two things: instance variables and methods. The topic of methods is.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
Run-Time Storage Organization
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Lecture From Chapter 6 & /8/10 1 Method of Classes.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
SE-1010 Dr. Mark L. Hornick 1 Defining Your Own Classes Part 3.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
A Closer Look at Methods and Classes. Overloading Methods In Java it is possible to define two or more methods within the same class that share the same.
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.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
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.
What is an Object? Real world objects are things that have: 1) state 2) behavior Example: your dog: 1) state – name, color, breed, sits?, barks?, wages.
Supervisor Ebtsam AbdelHakam Department of Computer Science Najran University 24/2/2014 Ebtsam Abdelhakam 1.
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.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
L EC. 06: C LASS D ETAILS S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length.
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,
L EC. 07: I NHERITANCE S PRING C ONTENT  Inheritance basics  Member access and inheritance  Constructors and inheritance  Superclass references.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Overloading Methods In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations.
Department of Computer Engineering Methods Computer Programming for International Engineers.
Method OverloadingtMyn1 Method overloading Methods of the same name can be declared in the same class, as long as they have different sets of parameters.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
1 CLASSES. 2 Class Fundamentals It defines a new data type Once defined, this new type can be used to create objects of that type A class is a template.
Constructor OverloadingtMyn1 Constructor Overloading One context in which you will regularly need to use overloading is when you write constructors for.
Method overloading contd class OverloadDemo { public static void main(String args[]) { Overload ob = new Overload(); int resI; double resD; // call all.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Classes - Intermediate
Methods.
Methods main concepts – method call – object 's methods – actual parameters – method declaration – formal parameters – return value other concepts – method.
(C) 2010 Pearson Education, Inc. All rights reserved.  Best way to develop and maintain a large program is to construct it from small, simple pieces,
Methods and Classes. Method Overloading Two or more methods within the same class that share the same name but different parameters class OverloadDemo.
Integer, Double, and Other Wrapper Classes … Sometimes a primitive value needs to be passed in as an argument, but the method definition creates an object.
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.
J AVA P ROGRAMMING 2 CH 04: C LASSES, O BJECTS AND M ETHODS (II) 0.
OOP Features Object Oriented Programming Main issues in software engineering – –maintainability, reusability, portability, security, integrity, user.
Defining Your Own Classes II
Functions + Overloading + Scope
Topic: Classes and Objects
CS212: Object Oriented Analysis and Design
Constructor Overloading
An Introduction to Java – Part I, language basics
Group Status Project Status.
Classes and Objects 5th Lecture
Parameters and Overloading
CS2011 Introduction to Programming I Methods (II)
JAVA Constructors.
Chapter 6 Methods.
JAVA 22 February 2019 DEPARTMENT OF CSE.
Java Programming Language
Lecture 11 Parameters CSE /26/2018.
Corresponds with Chapter 5
Presentation transcript:

L EC. 06: C LASS D ETAILS (2/2) 0

2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length Arguments [ 不測驗,可列補充教材 ]  Recursion  Using the keyword static  Nested classes  Shadowing 1

P ASSING ARGUMENTS  There are several ways to implement passing arguments from a caller to a invoked method, such as call-by-value and call-by-reference.  Java only supports call-by-value.  In Java, the precise effect differs between whether the argument type is a primitive type or a reference/class type. 2

C ALL - BY - VALUE APPROACH  The call-by-value approach copies the value of an argument into the space of corresponding formal parameter.  The argument is evaluated prior to the execution of invoked method.  The invoked method does not know where arguments are.  Changes made to the parameter of the method have no effect on the argument in the call. 3

E XAMPLE class Test { void noChange(int i, int j) { i = i + j; j = -j; } class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.println("a and b before call: " + a + " " + b); ob.noChange(a, b); System.out.println("a and b after call: " + a + " " + b); } 4 a and b before call: a and b after call: ob noChange(int i, int j)

E XERCISE 1 5  Create a stack class called Stack. Calls methods push() and pop() to access the stack. Keep all members of the Stack class private top [0] [1] [2] 21 4

 Hint: class stack { private int stack_data[]; private int stack_top; stack(int size) { … } public int push(int data) { … } public int pop() { … } 6 Handle abnormal situation class Ex1 { public static void main(String[] args) { stack s1 = new stack(100); s1.push(4); s1.push(21); System.out.println(s1.pop()); }

P ASSING REFERENCE TYPE ARGUMENTS IN J AVA  Since the content of a reference variable is the reference of an object, passing a reference type argument copies the reference of the object pointed by the argument to the memory of the corresponding parameter.  Remember that the content of a reference variable is the reference of an object, instead of the actual object.  The invoked method can access the object pointed by the argument through the parameter.  Passing reference type arguments has similar effect to call-by-reference. 7

E XAMPLE class Test { int a, b; Test(int i, int j) { a = i; b = j; } void change(Test obj) { a = obj.a + obj.b; b = -obj.b; } class PassObjRef { public static void main(String args[]) { Test ob = new Test(15, 20); System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.change(ob); System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b); } 8 ob.a and ob.b before call: ob.a and ob.b after call: ob a b change() obj

M ETHOD OVERLOADING  In Java, two or more methods within the same class can share the same name, as long as their parameter declarations are different.  When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading.  When an overloaded method is called, the version of the method whose parameters match the arguments is executed.  Numerical promotion and boxing may apply, but the automatic conversions apply only if there is no direct match between a parameter and an argument. 9

E XAMPLE class Overload { void ovlDemo() { System.out.println("No parameters"); } void ovlDemo(int a) { System.out.println("One parameter: " + a); } int ovlDemo(int a, int b) { System.out.println("Two parameters: " + a + " " + b); return a + b; } double ovlDemo(double a, double b) { System.out.println("Two double parameters: " + a + " "+ b); return a + b; } 10 No parameters One parameter: 2 Two parameters: 4 6 Result of ob.ovlDemo(4, 6): 10 Two double parameters: Result of ob.ovlDemo(1.1, 2.2): 3.42

class OverloadDemo { public static void main(String args[]) { Overload ob = new Overload(); int resI; double resD; // call all versions of ovlDemo() ob.ovlDemo(); ob.ovlDemo(2); resI = ob.ovlDemo(4, 6); System.out.println("Result of ob.ovlDemo(4, 6): " + resI); resD = ob.ovlDemo(1.1, 2.32); System.out.println("Result of ob.ovlDemo(1.1, 2.2): " + resD); } 11

E XAMPLE class Overload2 { void f(int x) { System.out.println("Inside f(int): " + x); } void f(double x) { System.out.println("Inside f(double): " + x); } 12 Inside f(int): 10 Inside f(double): 10.1 Inside f(int): 99 Inside f(int): 10 Inside f(double): 11.5

class TypeConv { public static void main(String args[]) { Overload2 ob = new Overload2(); int i = 10; double d = 10.1; byte b = 99; short s = 10; float f = 11.5F; ob.f(i); // calls ob.f(int) ob.f(d); // calls ob.f(double) ob.f(b); // calls ob.f(int)  type conversion ob.f(s); // calls ob.f(int)  type conversion ob.f(f); // calls ob.f(double)  type conversion } 13 byteshortintfloatdouble

E XAMPLE class MyClass { int x; MyClass() { System.out.println("Inside MyClass()."); x = 0; } MyClass(int i) { System.out.println("Inside MyClass(int)."); x = i; } MyClass(double d) { System.out.println("Inside MyClass(double)."); x = (int) d; } MyClass(int i, int j) { System.out.println("Inside MyClass(int, int)."); x = i * j; } 14 Inside MyClass(). Inside MyClass(int). Inside MyClass(double). Inside MyClass(int, int). t1.x: 0 t2.x: 88 t3.x: 17 t4.x: 8

class OverloadConsDemo { public static void main(String args[]) { MyClass t1 = new MyClass(); MyClass t2 = new MyClass(88); MyClass t3 = new MyClass(17.23); MyClass t4 = new MyClass(2, 4); System.out.println("t1.x: " + t1.x); System.out.println("t2.x: " + t2.x); System.out.println("t3.x: " + t3.x); System.out.println("t4.x: " + t4.x); } 15

B INDING FOR METHOD OVERLOADING  Binding is the process for creating the association between data/code with an identifier.  Static binding means that binding is done during compilation.  Dynamic binding means that binding is done during execution.  Binding for overloaded methods is static binding. 16

E XAMPLE class OverloadA { public static void main(String args[]) { OverloadA obj = new OverloadA(); obj.toDo(1); // C0 obj.toDo(2, 3); // C1 obj.toDo('a', 3); // C2 obj.toDo(2, 3, 4); // C3 obj.toDo(2, 3.2f); // C4 } void toDo(int i, int j) { // executed by C1 and C2 System.out.print("A"); } void toDo(int i, int... j) { // executed by C0 and C3 System.out.print("B"); } void toDo(double i, double j){ // executed by C4 System.out.print("C"); } 17 BAABC promotion

E XAMPLE class OverloadB { public static void main(String args[]) { OverloadB obj = new OverloadB(); obj.toDo(2, 3, 4); // ambiguous obj.toDo(3.2f); // cause error } void toDo(int i, int j, int... k) { System.out.print("A"); } void toDo(int i, int... j) { System.out.print("B"); } void toDo(Double i) { System.out.print("C"); } } 18

19 OverloadB.java:5: error: no suitable method found for toDo(float) obj.toDo(3.2f); ^ method OverloadB.toDo(int,int,int...) is not applicable (argument mismatch; possible lossy conversion from float to int) method OverloadB.toDo(int,int...) is not applicable (argument mismatch; possible lossy conversion from float to int) method OverloadB.toDo(Double) is not applicable (argument mismatch; float cannot be converted to Double) Note. It will not perform numerical promotion followed by boxing.

裝箱 ( BOXING ) 、拆箱 ( UNBOXING ) 20  把 primitive 轉成物件,稱之為裝箱  把物件轉乘 primitive ,稱之為拆箱  Ex. Integer A = new Integer(10); // 裝箱 int b = A.intValue(); // 拆箱 b = A; // 自動拆箱 A = 20; // 自動裝箱 A 10

class VarArgs { static void vaTest(int... v) { System.out.println("Number of args: " + v.length); for(int i=0; i < v.length; i++) System.out.println(v[i]); System.out.println(); } public static void main(String args[]) { vaTest(10); vaTest(1, 2, 3) vaTest(); } 21 Number of args: 1 10 Number of args: Number of args: 0 V ARIABLE - LENGTH A RGUMENTS

E XAMPLE class VarArgs2 { static void vaTest(int msg, int... v) { System.out.println("-->" + v.length); for(int i=0; i < v.length; i++) System.out.println(v[i]); System.out.println(); } public static void main(String args[]) { vaTest(100); vaTest(100, 1, 2, 3); } 22 -->0 --> Need at least one parameter 2 hr