尊敬的 微信汇率:1円 ≈ 0.046166 元 支付宝汇率:1円 ≈ 0.046257元 [退出登录]
SlideShare a Scribd company logo
Pass objects to methods
class block{
int a,b,c,volume;
block(int i,int j,int k){
i=a;
j=b;
k=c;
volume=a*b*c;
}
boolean sameBlock(block ob){
if(ob.a== a) & (ob.b==b) & (ob.c==c)
return true;
else
return false;
}
boolean sameVolume(block ob){
if(ob.volume==volume)
return true;
else
return false;
}
}//end of class
class passob{
public static void main(string args[]){
block ob1=new block (10,2,5);
block ob2=new block (10,2,5);
block ob3=new block (4,5,5);
System.out.println(“ob1 is same dimensions as ob2:”+ob1.sameBlock(ob2));
System.out.println(“ob1 is same dimensions as ob3:”+ob1.sameBlock(ob3));
System.out.println(“ob1 has same volume as ob3:”+ob1.sameVolume(ob3));
}//end of main
}// end of class
• The sameblock() and sameVolume() methods compare
the block object passed as parameter to the invoking
object.
• Sameblock() , the dimensions of the objects are
compared and true is returned only if the two blocks are
the same.
• samVolume() returns true if the sent object and invoked
object has same volume.
How arguments are passed
• Two ways
– Call-by-value
– Call-by-reference
• Call-by-value  copies the value of the
argument into the format parameter of the
subroutine.
• Changes made to the parameter of the
subroutine have no effect on the argument call.
• Call-by-reference a reference to an argument
is passed to the parameter, inside the
subroutine, this reference is used to access the
actual argument specified in the call
• When you pass primitive data types such as int
or double, to a method, it is passed by value.
• A copy of the argument is made and that is what
occurs to the parameter that receives the
argument and has no effect outside the method.
• Consider the following program
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();
itn a=15,b=20;
System.out.println(“before the call:a=”+a”and b=“+b);
ob.noChange(a,b);
System.out.println(“after the call:a=”+a”and b=“+b);
}
}
• Output
• Before call : a=15 b=20
• After call: a=15 b=20
• When you pass the object into the method, the situation
changes dramatically because the objects are implicitly
passed by reference
• Create a variable of class type, a reference is created to
an object.
• This reference is passed as parameter , which is referred
by the argument.
class Test{
int a , b;
Test(int i,int j){
a=i;
b=j;
}
void change(Test ob){
ob.a=ob.a+ob.b;
ob.b=-ob.b;
}
}
class CallByRef{
public static void main(String
args[]){
Test ob=new Test(15,20);
System.out.println(“before the
call:a=”+ob.a”and b=“+ob.b);
ob.Change(ob);
System.out.println(“after the
call:a=”+ob.a”and b=“+ob.b);
}
}
• Output:
• Before call :a= 15 b=20
• After call : a=35 b= -20
• When a object is passed to a method , the reference
itself is passed by the use of call-by-value
Returning the objects
• A method can return any type of data including class
types.
• In class ErrorMsg, used to report errors there is a
method called getErrorMsg() which returns a String
object that contains a description of an error based upon
the error code that is passed.
class ErrorMsg{
String msgs[]={ “output
error”, “input error”,”disk
full”, index-out-of-bound”};
String getErrorMsg(int i){
if(i>=0 & i<msgs.length)
return msgs[i];
Else
return “invalid error code”;
}
class ErrMsg{
public static void main(String args[]){
ErrorMsg err=new ErrorMsg();
System.out.println(err.getErrorMsg(2));
System.out.println(err.getErrorMsg(19));
}
}
Output:
Disk full
Invalid error code
Method overloading
• Two or more methods within the same class can share
the same name, as long as their parameters declarations
are different.
• Then in such case the methods are called , overloaded.
• Process is called method overloading
• It is one of the way Java implements the polymorphism
• Restriction is : the type or number of the parameters of
each overloaded methods must differ.
• It is not sufficient if they have different return types.
• When an overloaded method is called, the version of the
method whose parameters match the arguments is
executed.
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
parameter:”+a +” and ”+b);
return a+b;
}
}
class OverloadDemo{
public static void main(String
args[]){
Overload o=new Overload();
int result;
o.ovlDemo();
o.ovlDemo(2);
result=o.ovlDemo(4,6);
System.out.println(“Result
:”+result);
}
}
void ovlDemo(int a)
{
System.out.println(“One parameter:”+a);
}
----
int ovlDemo(int a)
{
System.out.println(“One parameter:”+a);
return a*a;
}
Will throw an error, ie. Their return types are insufficient for
performing overloading
What is signature term used by
java programmers?
• A signature is the name of the method plus its parameter
list
• No two methods within the same class can have the
same signature.
• It does not include return type
Overloading constructors
• Constructors can also be overloaded like methods of a
class
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;
}
}//end of Myclass
class OverLoadConstructorDemo{
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);
}
}
• Output
Inside Myclass()
Inside Myclass(int)
Inside Myclass(double)
Inside Myclass(int,int)
t1.x=0
t1.x=88
t1.x=17
t1.x=8
Recursion
• A method calling itself , this process is called recursion.
• A method that calls itself is said to be recursive
• The key component of a recursive method is a statement
that executes a call by itself.
• Eg: The factorial of a number until number N.
• When a method calls itself , new local variables and
parameters are allocated storage on the stack, the
method code is executed with these new variables from
the start.
• A recursive call does not make a copy of the method.
• Each recursive call returns, the old variables and
parameters are removed from the stack and
execution resumes at a point of call inside the
method.
• Recursive methods could be said to “telescope”
out and back.
A simple example of recursion
class Factorial{
int factR(int n){
int result;
if(n ==1)
return 1;
result=fact(n-1)*n;
return result;
}
} //end of class factorial
class Recursion{
public static void main(String args[]){
Factorial f= new Factorial ();
System.out.println(“factorial of 3 is ”+f.factR(3));
System.out.println(“factorial of 4 is ”+f.factR(4));
System.out.println(“factorial of 5 is ”+f.factR(5));
}//end of main
}// end of Recursion
• Output:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
• When factR() function is called with an argument of 1, the
method returns 1 otherwise it returns the product of
factR(n-1)*n;
• To evaluate this expression, the factR() is called with
value n-1
• This process repeats until n equals 1 and the calls to the
method begin running.
• Recursive methods where there are in huge
numbers, it will take a longer time to complete
than iterative methods.
• Too many recursive calls to a method could
cause the stack to overrun
• Storage of local variables and parameters are
allocated in the stack, every time a call is made,
it creates a new copy of these variables. There
is possibility that stack can get exhausted.
• If this happens, the java run time machine will
cause an exception.
Understanding static
• When you want to define a class member that will be
used independently of any object of that class, without
any reference to a specific instance
• To create such a member, precede its declaration with
the keyword static.
• When a member is declared as static, it can be
accessed before any objects of its class are created.
And without any reference to any object.
• You can declare both the data variables and methods as
static.
• Common example for static is main() function.
• main() is declared as static because it must be called by the
JVM when your program begins.
• Outside the class, to use a static member , you need to
specify the name of the class followed by the dot operator
• No objects has to be created.
• If you assign the value 10 to a static variable called count that
is part of Timer class,
Timer.count=10;
• Variables declared as static are essentially global variables
• When an object is declared no copy of static variable is made
• All instances of the class share the same static variable
class StaticDemo{
int x;
static int y;
int sum(){
return x+y;
}
}
class Sdemo{
public static void main(String args[]){
StaticDemo ob1=new StaticDemo();
StaticDemo ob2=new StaticDemo();
ob1.x=10;
ob2.x=20;
System.out.println(“of course, ob1.x and
ob2.x are independent”);
System.out.println(“ob1.x: ”+ob1.x+” “
+”ob2.x: ”+ob2.x);
System.out.println(“Static variable y is
shared”);
StaticDemo.y=19;
System.out.println(“Set StaticDemo.y to
19”);
System.out.println(“ob1.sum:”+ob1.sum());
System.out.println(“ob2.sum:”+ob2.sum());
StaticDemo.y=100;
System.out.println(“change StaticDemo.y to
100”);
System.out.println(“ob1.sum:”+ob1.sum());
System.out.println(“ob2.sum:”+ob2.sum());
}
}
• Output
Of course, ob1.x and ob2.x are independent
ob1.x=10
ob2.x=20
Static variable y is shared.
Set staticdemo.y to 19
ob1.sum():29
ob2.sum():39
Change staticDemo.y to 100
ob1.sum():110
ob2.sum():120
• The difference between static method and normal
method is that static method is called through its class
name, without any object of that class being created.
• Method declared as static have several restrictions
– They can directly call only other static methods
– They can directly access only static data
– They do not have this reference.
class StaticError{
int demon=3; // a normal instance variable
static int val=1024;
static int valDivDemon(){
return val/denom; //wont compile
}
}
Static blocks
• A class will require some type of initialization before it is
ready to create objects.
• Eg: establishing a connection to a remote site.
• Java allows you to declare a static block
• A static block is executed when the class is first loaded,
hence it is executed before the class can be used for any
other purpose
class staticblock{
static double rootof2;
static double rootof3;
static{
System.out.println(“Inside
the static block.”);
rootof2=Math.sqrt(2.0);
rootof3=Math.sqrt(3.0);
}
StaticBlock(String msg){
System.out.println(msg);
} //end of staticblock
class SDemo{
public static void main(String
args[]){
StaticBlock ob=new
StaticBlock(“Inside
Constructor”);
System.out.println(“SquareRo
ot of 2
is:”+StaticBlock.rootof2);
System.out.println(“SquareRo
ot of 3
is:”+StaticBlock.rootof3);
} //end of main
}//end of staticblock
• Output
Inside static block
Inside constructor
Square root of 2 is 1.414213
Square root of 3 is 1.732050
Introducing nested and inner
classes
• A class declared inside another class is called nested
class.
• A nested class does not exists independently of its
enclosing class
• Scope of nested class is bounded by its outer class.
• A nested class that is declared directly within its
enclosing class scope is a member of its enclosing class.
• It is possible to declare a nested class that is local to a
block.
• There are two types of nested class :
– Preceded by a static modifier
– Those that are not preceded by static modifier
• Inner class it has access to all of the variables and
methods of its outer class and may refer to them directly
in the same way that other non-static members of outer
class
• Inner class is used to provide a set of services that is
used only by its enclosing class.
class Outer{
int nums[];
Outer(int n[]){
nums=n;
}
void analyze(){
Inner inob=new Inner();
S.O.P(“min:”+inob.min());
S.O.P(“max”+inob.max());
S.O.P(“avg:”+inob.abg());
}
}
class Inner{
int min(){
int m=nums[0];
for(int i=1; i<nums.length;i++)
if(nums[i]<m)
m=nums[i];
return m;
}
int max(){
int m=nums[0];
for(int i=1; i<nums.length;i++)
if(nums[i]>m)
m=nums[i];
return m;
}
int avg(){
int a=0;
for(int i=0;i<nums.length;i++)
a+=nums[i];
return a/nums.length;
}
}
class nestedClassDemo{
public static void main(String
args[]){
int x[]={3,2,1,5,6,9,7,8};
Outer o=new Outer(x);
o.analyze();
}
}
• Output
mini:1
max:9
avg:5
Varags: variable length
arguements
• Used when the number of argument list is not fixed in a
method
• For example: A method that opens an internet
connection might take a user name, password ,
filename, protocol and so on, but supply defaults if some
of this information is not provided.
• Earlier two different ways it is handled, when maximum
number of arguments was known, then you could
overload version of the method, one for each way the
method could be could.
• Second approach , is to put all the arguments into an
array and then array is passed into the method.
• Both of these methods resulted in clumsy situations.
• JDK 5 onwards, it included the feature that is simplified
the creation of methods that require a variable number of
arguments, called as varargs- variable length arguments.
• A method that takes a variable number of is called
variable-arity method or simply varargs method.
• The parameter list for a varargs method is not fixed, but
rather variable in length.
Varargs basics
• Variable length argument is specified by three periods
(…)
static void vaTest(int … v){
System.out.println(“Number of args:”+v.length);
System.out.println(“Contents:”);
for(int i=0;i<v.length;i++)
System.out.println(“arg ”+i+”:”+v[i]);
System.out.println();
}
• Here vaTest() method can be called with zero or more
arguments.
• It causes v to be implicitly declared as an array of the
type int []
class Varargs{
static void vaTest(int … v){
System.out.println(“Number of args:”+v.length);
System.out.println(“Contents:”);
for(int i=0;i<v.length;i++)
System.out.println(“arg ”+i+”:”+v[i]);
System.out.println();
}//end of vaTest
public static void main(String args[]){
vaTest(10);
vaTest(1,2,3);
vaTest();
}//end of main
} //end of class
• A method can have normal parameters along with the
variable-length parameter
• However the variable –length parameter must be last
parameter declared by the method.
• Eg: int doIt(int a,int b, int … vals){
}
In this case if the function call should have first two
parameters as int type, after two parameters it can have
any type will be stored in vals.
int doIT(int a, int b, double c,int … vals, double .. morevals)
{
..
}
• The attempt to declare the second varargs parameters is
illegal.
Overloading Varargs Methods
• You can overload a method that takes a variable-length
argument
• Following program overloads vaTest() three times.
• Varargs can be overloaded in two ways
• First , the types of its varag parameter can differ i.e.
varTest(int … ) and vaTest(boolean …)
• Second way is to add one or more normal parameters
• vaTest(String msg, int … )
Varargs and Ambiguity
• It is possible to create an ambiguous to an overload
varargs method.
class varargs4{
static void vaTest(int … v){
// …
}
static void vaTest(boolean … v){
//…
}
public static void main(String args[]){
vaTest(1,2,3);
vaTest(true, false,false);
vaTest(); // lead to confusion
}
}
static void vaTest(int … v) {
//
}
static void vaTest(int n, int …v){
//
}
vaTest(1); // the compiler cannot resolve this kind of call,
hence it will through an error.

More Related Content

What's hot

The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88
Mahmoud Samir Fayed
 
Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
Manusha Dilan
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
VEERA RAGAVAN
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
sidra tauseef
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
RACHIT_GUPTA
 
(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual
Chandrapriya Jayabal
 
The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30
Mahmoud Samir Fayed
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
Radim Pavlicek
 
The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31
Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 37 of 189
The Ring programming language version 1.6 book - Part 37 of 189The Ring programming language version 1.6 book - Part 37 of 189
The Ring programming language version 1.6 book - Part 37 of 189
Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 38 of 202
The Ring programming language version 1.8 book - Part 38 of 202The Ring programming language version 1.8 book - Part 38 of 202
The Ring programming language version 1.8 book - Part 38 of 202
Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202
Mahmoud Samir Fayed
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
Chhom Karath
 
C#
C#C#
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
pramode_ce
 
The Ring programming language version 1.5.1 book - Part 30 of 180
The Ring programming language version 1.5.1 book - Part 30 of 180The Ring programming language version 1.5.1 book - Part 30 of 180
The Ring programming language version 1.5.1 book - Part 30 of 180
Mahmoud Samir Fayed
 
Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
Paweł Byszewski
 
The Ring programming language version 1.7 book - Part 36 of 196
The Ring programming language version 1.7 book - Part 36 of 196The Ring programming language version 1.7 book - Part 36 of 196
The Ring programming language version 1.7 book - Part 36 of 196
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 33 of 184
The Ring programming language version 1.5.3 book - Part 33 of 184The Ring programming language version 1.5.3 book - Part 33 of 184
The Ring programming language version 1.5.3 book - Part 33 of 184
Mahmoud Samir Fayed
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
Vaclav Pech
 

What's hot (20)

The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88
 
Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual
 
The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
 
The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31
 
The Ring programming language version 1.6 book - Part 37 of 189
The Ring programming language version 1.6 book - Part 37 of 189The Ring programming language version 1.6 book - Part 37 of 189
The Ring programming language version 1.6 book - Part 37 of 189
 
The Ring programming language version 1.8 book - Part 38 of 202
The Ring programming language version 1.8 book - Part 38 of 202The Ring programming language version 1.8 book - Part 38 of 202
The Ring programming language version 1.8 book - Part 38 of 202
 
The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
C#
C#C#
C#
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
The Ring programming language version 1.5.1 book - Part 30 of 180
The Ring programming language version 1.5.1 book - Part 30 of 180The Ring programming language version 1.5.1 book - Part 30 of 180
The Ring programming language version 1.5.1 book - Part 30 of 180
 
Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
 
The Ring programming language version 1.7 book - Part 36 of 196
The Ring programming language version 1.7 book - Part 36 of 196The Ring programming language version 1.7 book - Part 36 of 196
The Ring programming language version 1.7 book - Part 36 of 196
 
The Ring programming language version 1.5.3 book - Part 33 of 184
The Ring programming language version 1.5.3 book - Part 33 of 184The Ring programming language version 1.5.3 book - Part 33 of 184
The Ring programming language version 1.5.3 book - Part 33 of 184
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 

Similar to Chap2 class,objects contd

Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
UNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxUNIT_-II_2021R.pptx
UNIT_-II_2021R.pptx
RDeepa9
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
ShashikantSathe3
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
Infoviaan Technologies
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
Soumya Behera
 
nested_Object as Parameter & Recursion_Later_commamd.pptx
nested_Object as Parameter  & Recursion_Later_commamd.pptxnested_Object as Parameter  & Recursion_Later_commamd.pptx
nested_Object as Parameter & Recursion_Later_commamd.pptx
Kongu Engineering College, Perundurai, Erode
 
Core java Essentials
Core java EssentialsCore java Essentials
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
Second chapter-java
Second chapter-javaSecond chapter-java
Second chapter-java
Ahmad sohail Kakar
 
Thread
ThreadThread
Thread
phanleson
 
7
77
Core C#
Core C#Core C#
Second chapter-java
Second chapter-javaSecond chapter-java
Second chapter-java
Ahmad sohail Kakar
 
Comp102 lec 7
Comp102   lec 7Comp102   lec 7
Comp102 lec 7
Fraz Bakhsh
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
mcollison
 
Java Generics
Java GenericsJava Generics
Java Generics
jeslie
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
Geetha Manohar
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
Simon Ritter
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
Muhammad Fayyaz
 

Similar to Chap2 class,objects contd (20)

Java Programs
Java ProgramsJava Programs
Java Programs
 
UNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxUNIT_-II_2021R.pptx
UNIT_-II_2021R.pptx
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
nested_Object as Parameter & Recursion_Later_commamd.pptx
nested_Object as Parameter  & Recursion_Later_commamd.pptxnested_Object as Parameter  & Recursion_Later_commamd.pptx
nested_Object as Parameter & Recursion_Later_commamd.pptx
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Second chapter-java
Second chapter-javaSecond chapter-java
Second chapter-java
 
Thread
ThreadThread
Thread
 
7
77
7
 
Core C#
Core C#Core C#
Core C#
 
Second chapter-java
Second chapter-javaSecond chapter-java
Second chapter-java
 
Comp102 lec 7
Comp102   lec 7Comp102   lec 7
Comp102 lec 7
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 

More from raksharao

Unit 1-logic
Unit 1-logicUnit 1-logic
Unit 1-logic
raksharao
 
Unit 1 rules of inference
Unit 1  rules of inferenceUnit 1  rules of inference
Unit 1 rules of inference
raksharao
 
Unit 1 quantifiers
Unit 1  quantifiersUnit 1  quantifiers
Unit 1 quantifiers
raksharao
 
Unit 1 introduction to proofs
Unit 1  introduction to proofsUnit 1  introduction to proofs
Unit 1 introduction to proofs
raksharao
 
Unit 7 verification &amp; validation
Unit 7 verification &amp; validationUnit 7 verification &amp; validation
Unit 7 verification &amp; validation
raksharao
 
Unit 6 input modeling problems
Unit 6 input modeling problemsUnit 6 input modeling problems
Unit 6 input modeling problems
raksharao
 
Unit 6 input modeling
Unit 6 input modeling Unit 6 input modeling
Unit 6 input modeling
raksharao
 
Unit 5 general principles, simulation software
Unit 5 general principles, simulation softwareUnit 5 general principles, simulation software
Unit 5 general principles, simulation software
raksharao
 
Unit 5 general principles, simulation software problems
Unit 5  general principles, simulation software problemsUnit 5  general principles, simulation software problems
Unit 5 general principles, simulation software problems
raksharao
 
Unit 4 queuing models
Unit 4 queuing modelsUnit 4 queuing models
Unit 4 queuing models
raksharao
 
Unit 4 queuing models problems
Unit 4 queuing models problemsUnit 4 queuing models problems
Unit 4 queuing models problems
raksharao
 
Unit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generationUnit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generation
raksharao
 
Unit 1 introduction contd
Unit 1 introduction contdUnit 1 introduction contd
Unit 1 introduction contd
raksharao
 
Unit 1 introduction
Unit 1 introductionUnit 1 introduction
Unit 1 introduction
raksharao
 
Module1 part2
Module1 part2Module1 part2
Module1 part2
raksharao
 
Module1 Mobile Computing Architecture
Module1 Mobile Computing ArchitectureModule1 Mobile Computing Architecture
Module1 Mobile Computing Architecture
raksharao
 
java-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of appletjava-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of applet
raksharao
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
raksharao
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 

More from raksharao (20)

Unit 1-logic
Unit 1-logicUnit 1-logic
Unit 1-logic
 
Unit 1 rules of inference
Unit 1  rules of inferenceUnit 1  rules of inference
Unit 1 rules of inference
 
Unit 1 quantifiers
Unit 1  quantifiersUnit 1  quantifiers
Unit 1 quantifiers
 
Unit 1 introduction to proofs
Unit 1  introduction to proofsUnit 1  introduction to proofs
Unit 1 introduction to proofs
 
Unit 7 verification &amp; validation
Unit 7 verification &amp; validationUnit 7 verification &amp; validation
Unit 7 verification &amp; validation
 
Unit 6 input modeling problems
Unit 6 input modeling problemsUnit 6 input modeling problems
Unit 6 input modeling problems
 
Unit 6 input modeling
Unit 6 input modeling Unit 6 input modeling
Unit 6 input modeling
 
Unit 5 general principles, simulation software
Unit 5 general principles, simulation softwareUnit 5 general principles, simulation software
Unit 5 general principles, simulation software
 
Unit 5 general principles, simulation software problems
Unit 5  general principles, simulation software problemsUnit 5  general principles, simulation software problems
Unit 5 general principles, simulation software problems
 
Unit 4 queuing models
Unit 4 queuing modelsUnit 4 queuing models
Unit 4 queuing models
 
Unit 4 queuing models problems
Unit 4 queuing models problemsUnit 4 queuing models problems
Unit 4 queuing models problems
 
Unit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generationUnit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generation
 
Unit 1 introduction contd
Unit 1 introduction contdUnit 1 introduction contd
Unit 1 introduction contd
 
Unit 1 introduction
Unit 1 introductionUnit 1 introduction
Unit 1 introduction
 
Module1 part2
Module1 part2Module1 part2
Module1 part2
 
Module1 Mobile Computing Architecture
Module1 Mobile Computing ArchitectureModule1 Mobile Computing Architecture
Module1 Mobile Computing Architecture
 
java-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of appletjava-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of applet
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 

Recently uploaded

Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...
Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...
Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...
IJCNCJournal
 
My Airframe Metallic Design Capability Studies..pdf
My Airframe Metallic Design Capability Studies..pdfMy Airframe Metallic Design Capability Studies..pdf
My Airframe Metallic Design Capability Studies..pdf
Geoffrey Wardle. MSc. MSc. Snr.MAIAA
 
Sachpazis_Consolidation Settlement Calculation Program-The Python Code and th...
Sachpazis_Consolidation Settlement Calculation Program-The Python Code and th...Sachpazis_Consolidation Settlement Calculation Program-The Python Code and th...
Sachpazis_Consolidation Settlement Calculation Program-The Python Code and th...
Dr.Costas Sachpazis
 
Call Girls Chennai +91-8824825030 Vip Call Girls Chennai
Call Girls Chennai +91-8824825030 Vip Call Girls ChennaiCall Girls Chennai +91-8824825030 Vip Call Girls Chennai
Call Girls Chennai +91-8824825030 Vip Call Girls Chennai
paraasingh12 #V08
 
🔥 Hyderabad Call Girls  👉 9352988975 👫 High Profile Call Girls Whatsapp Numbe...
🔥 Hyderabad Call Girls  👉 9352988975 👫 High Profile Call Girls Whatsapp Numbe...🔥 Hyderabad Call Girls  👉 9352988975 👫 High Profile Call Girls Whatsapp Numbe...
🔥 Hyderabad Call Girls  👉 9352988975 👫 High Profile Call Girls Whatsapp Numbe...
aarusi sexy model
 
The Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC Conduit
The Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC ConduitThe Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC Conduit
The Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC Conduit
Guangdong Ctube Industry Co., Ltd.
 
High Profile Call Girls Ahmedabad 🔥 7737669865 🔥 Real Fun With Sexual Girl Av...
High Profile Call Girls Ahmedabad 🔥 7737669865 🔥 Real Fun With Sexual Girl Av...High Profile Call Girls Ahmedabad 🔥 7737669865 🔥 Real Fun With Sexual Girl Av...
High Profile Call Girls Ahmedabad 🔥 7737669865 🔥 Real Fun With Sexual Girl Av...
dABGO KI CITy kUSHINAGAR Ak47
 
Basic principle and types Static Relays ppt
Basic principle and  types  Static Relays pptBasic principle and  types  Static Relays ppt
Basic principle and types Static Relays ppt
Sri Ramakrishna Institute of Technology
 
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdfSELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
Pallavi Sharma
 
MODULE 5 BIOLOGY FOR ENGINEERS TRENDS IN BIO ENGINEERING.pptx
MODULE 5 BIOLOGY FOR ENGINEERS TRENDS IN BIO ENGINEERING.pptxMODULE 5 BIOLOGY FOR ENGINEERS TRENDS IN BIO ENGINEERING.pptx
MODULE 5 BIOLOGY FOR ENGINEERS TRENDS IN BIO ENGINEERING.pptx
NaveenNaveen726446
 
Technological Innovation Management And Entrepreneurship-1.pdf
Technological Innovation Management And Entrepreneurship-1.pdfTechnological Innovation Management And Entrepreneurship-1.pdf
Technological Innovation Management And Entrepreneurship-1.pdf
tanujaharish2
 
Cricket management system ptoject report.pdf
Cricket management system ptoject report.pdfCricket management system ptoject report.pdf
Cricket management system ptoject report.pdf
Kamal Acharya
 
🔥Independent Call Girls In Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Esco...
🔥Independent Call Girls In Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Esco...🔥Independent Call Girls In Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Esco...
🔥Independent Call Girls In Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Esco...
AK47
 
SPICE PARK JUL2024 ( 6,866 SPICE Models )
SPICE PARK JUL2024 ( 6,866 SPICE Models )SPICE PARK JUL2024 ( 6,866 SPICE Models )
SPICE PARK JUL2024 ( 6,866 SPICE Models )
Tsuyoshi Horigome
 
paper relate Chozhavendhan et al. 2020.pdf
paper relate Chozhavendhan et al. 2020.pdfpaper relate Chozhavendhan et al. 2020.pdf
paper relate Chozhavendhan et al. 2020.pdf
ShurooqTaib
 
Online train ticket booking system project.pdf
Online train ticket booking system project.pdfOnline train ticket booking system project.pdf
Online train ticket booking system project.pdf
Kamal Acharya
 
Mahipalpur Call Girls Delhi 🔥 9711199012 ❄- Pick Your Dream Call Girls with 1...
Mahipalpur Call Girls Delhi 🔥 9711199012 ❄- Pick Your Dream Call Girls with 1...Mahipalpur Call Girls Delhi 🔥 9711199012 ❄- Pick Your Dream Call Girls with 1...
Mahipalpur Call Girls Delhi 🔥 9711199012 ❄- Pick Your Dream Call Girls with 1...
simrangupta87541
 
CSP_Study - Notes (Paul McNeill) 2017.pdf
CSP_Study - Notes (Paul McNeill) 2017.pdfCSP_Study - Notes (Paul McNeill) 2017.pdf
CSP_Study - Notes (Paul McNeill) 2017.pdf
Ismail Sultan
 
Covid Management System Project Report.pdf
Covid Management System Project Report.pdfCovid Management System Project Report.pdf
Covid Management System Project Report.pdf
Kamal Acharya
 
Hot Call Girls In Bangalore ✔ 9079923931 ✔ Hi I Am Divya Vip Call Girl Servic...
Hot Call Girls In Bangalore ✔ 9079923931 ✔ Hi I Am Divya Vip Call Girl Servic...Hot Call Girls In Bangalore ✔ 9079923931 ✔ Hi I Am Divya Vip Call Girl Servic...
Hot Call Girls In Bangalore ✔ 9079923931 ✔ Hi I Am Divya Vip Call Girl Servic...
Banerescorts
 

Recently uploaded (20)

Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...
Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...
Particle Swarm Optimization–Long Short-Term Memory based Channel Estimation w...
 
My Airframe Metallic Design Capability Studies..pdf
My Airframe Metallic Design Capability Studies..pdfMy Airframe Metallic Design Capability Studies..pdf
My Airframe Metallic Design Capability Studies..pdf
 
Sachpazis_Consolidation Settlement Calculation Program-The Python Code and th...
Sachpazis_Consolidation Settlement Calculation Program-The Python Code and th...Sachpazis_Consolidation Settlement Calculation Program-The Python Code and th...
Sachpazis_Consolidation Settlement Calculation Program-The Python Code and th...
 
Call Girls Chennai +91-8824825030 Vip Call Girls Chennai
Call Girls Chennai +91-8824825030 Vip Call Girls ChennaiCall Girls Chennai +91-8824825030 Vip Call Girls Chennai
Call Girls Chennai +91-8824825030 Vip Call Girls Chennai
 
🔥 Hyderabad Call Girls  👉 9352988975 👫 High Profile Call Girls Whatsapp Numbe...
🔥 Hyderabad Call Girls  👉 9352988975 👫 High Profile Call Girls Whatsapp Numbe...🔥 Hyderabad Call Girls  👉 9352988975 👫 High Profile Call Girls Whatsapp Numbe...
🔥 Hyderabad Call Girls  👉 9352988975 👫 High Profile Call Girls Whatsapp Numbe...
 
The Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC Conduit
The Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC ConduitThe Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC Conduit
The Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC Conduit
 
High Profile Call Girls Ahmedabad 🔥 7737669865 🔥 Real Fun With Sexual Girl Av...
High Profile Call Girls Ahmedabad 🔥 7737669865 🔥 Real Fun With Sexual Girl Av...High Profile Call Girls Ahmedabad 🔥 7737669865 🔥 Real Fun With Sexual Girl Av...
High Profile Call Girls Ahmedabad 🔥 7737669865 🔥 Real Fun With Sexual Girl Av...
 
Basic principle and types Static Relays ppt
Basic principle and  types  Static Relays pptBasic principle and  types  Static Relays ppt
Basic principle and types Static Relays ppt
 
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdfSELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
 
MODULE 5 BIOLOGY FOR ENGINEERS TRENDS IN BIO ENGINEERING.pptx
MODULE 5 BIOLOGY FOR ENGINEERS TRENDS IN BIO ENGINEERING.pptxMODULE 5 BIOLOGY FOR ENGINEERS TRENDS IN BIO ENGINEERING.pptx
MODULE 5 BIOLOGY FOR ENGINEERS TRENDS IN BIO ENGINEERING.pptx
 
Technological Innovation Management And Entrepreneurship-1.pdf
Technological Innovation Management And Entrepreneurship-1.pdfTechnological Innovation Management And Entrepreneurship-1.pdf
Technological Innovation Management And Entrepreneurship-1.pdf
 
Cricket management system ptoject report.pdf
Cricket management system ptoject report.pdfCricket management system ptoject report.pdf
Cricket management system ptoject report.pdf
 
🔥Independent Call Girls In Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Esco...
🔥Independent Call Girls In Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Esco...🔥Independent Call Girls In Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Esco...
🔥Independent Call Girls In Pune 💯Call Us 🔝 7014168258 🔝💃Independent Pune Esco...
 
SPICE PARK JUL2024 ( 6,866 SPICE Models )
SPICE PARK JUL2024 ( 6,866 SPICE Models )SPICE PARK JUL2024 ( 6,866 SPICE Models )
SPICE PARK JUL2024 ( 6,866 SPICE Models )
 
paper relate Chozhavendhan et al. 2020.pdf
paper relate Chozhavendhan et al. 2020.pdfpaper relate Chozhavendhan et al. 2020.pdf
paper relate Chozhavendhan et al. 2020.pdf
 
Online train ticket booking system project.pdf
Online train ticket booking system project.pdfOnline train ticket booking system project.pdf
Online train ticket booking system project.pdf
 
Mahipalpur Call Girls Delhi 🔥 9711199012 ❄- Pick Your Dream Call Girls with 1...
Mahipalpur Call Girls Delhi 🔥 9711199012 ❄- Pick Your Dream Call Girls with 1...Mahipalpur Call Girls Delhi 🔥 9711199012 ❄- Pick Your Dream Call Girls with 1...
Mahipalpur Call Girls Delhi 🔥 9711199012 ❄- Pick Your Dream Call Girls with 1...
 
CSP_Study - Notes (Paul McNeill) 2017.pdf
CSP_Study - Notes (Paul McNeill) 2017.pdfCSP_Study - Notes (Paul McNeill) 2017.pdf
CSP_Study - Notes (Paul McNeill) 2017.pdf
 
Covid Management System Project Report.pdf
Covid Management System Project Report.pdfCovid Management System Project Report.pdf
Covid Management System Project Report.pdf
 
Hot Call Girls In Bangalore ✔ 9079923931 ✔ Hi I Am Divya Vip Call Girl Servic...
Hot Call Girls In Bangalore ✔ 9079923931 ✔ Hi I Am Divya Vip Call Girl Servic...Hot Call Girls In Bangalore ✔ 9079923931 ✔ Hi I Am Divya Vip Call Girl Servic...
Hot Call Girls In Bangalore ✔ 9079923931 ✔ Hi I Am Divya Vip Call Girl Servic...
 

Chap2 class,objects contd

  • 1. Pass objects to methods class block{ int a,b,c,volume; block(int i,int j,int k){ i=a; j=b; k=c; volume=a*b*c; } boolean sameBlock(block ob){ if(ob.a== a) & (ob.b==b) & (ob.c==c) return true; else return false; } boolean sameVolume(block ob){ if(ob.volume==volume) return true; else return false; } }//end of class
  • 2. class passob{ public static void main(string args[]){ block ob1=new block (10,2,5); block ob2=new block (10,2,5); block ob3=new block (4,5,5); System.out.println(“ob1 is same dimensions as ob2:”+ob1.sameBlock(ob2)); System.out.println(“ob1 is same dimensions as ob3:”+ob1.sameBlock(ob3)); System.out.println(“ob1 has same volume as ob3:”+ob1.sameVolume(ob3)); }//end of main }// end of class
  • 3. • The sameblock() and sameVolume() methods compare the block object passed as parameter to the invoking object. • Sameblock() , the dimensions of the objects are compared and true is returned only if the two blocks are the same. • samVolume() returns true if the sent object and invoked object has same volume.
  • 4. How arguments are passed • Two ways – Call-by-value – Call-by-reference • Call-by-value  copies the value of the argument into the format parameter of the subroutine. • Changes made to the parameter of the subroutine have no effect on the argument call. • Call-by-reference a reference to an argument is passed to the parameter, inside the subroutine, this reference is used to access the actual argument specified in the call
  • 5. • When you pass primitive data types such as int or double, to a method, it is passed by value. • A copy of the argument is made and that is what occurs to the parameter that receives the argument and has no effect outside the method. • Consider the following program
  • 6. 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(); itn a=15,b=20; System.out.println(“before the call:a=”+a”and b=“+b); ob.noChange(a,b); System.out.println(“after the call:a=”+a”and b=“+b); } }
  • 7. • Output • Before call : a=15 b=20 • After call: a=15 b=20
  • 8. • When you pass the object into the method, the situation changes dramatically because the objects are implicitly passed by reference • Create a variable of class type, a reference is created to an object. • This reference is passed as parameter , which is referred by the argument.
  • 9. class Test{ int a , b; Test(int i,int j){ a=i; b=j; } void change(Test ob){ ob.a=ob.a+ob.b; ob.b=-ob.b; } } class CallByRef{ public static void main(String args[]){ Test ob=new Test(15,20); System.out.println(“before the call:a=”+ob.a”and b=“+ob.b); ob.Change(ob); System.out.println(“after the call:a=”+ob.a”and b=“+ob.b); } }
  • 10. • Output: • Before call :a= 15 b=20 • After call : a=35 b= -20 • When a object is passed to a method , the reference itself is passed by the use of call-by-value
  • 11. Returning the objects • A method can return any type of data including class types. • In class ErrorMsg, used to report errors there is a method called getErrorMsg() which returns a String object that contains a description of an error based upon the error code that is passed.
  • 12. class ErrorMsg{ String msgs[]={ “output error”, “input error”,”disk full”, index-out-of-bound”}; String getErrorMsg(int i){ if(i>=0 & i<msgs.length) return msgs[i]; Else return “invalid error code”; } class ErrMsg{ public static void main(String args[]){ ErrorMsg err=new ErrorMsg(); System.out.println(err.getErrorMsg(2)); System.out.println(err.getErrorMsg(19)); } } Output: Disk full Invalid error code
  • 13. Method overloading • Two or more methods within the same class can share the same name, as long as their parameters declarations are different. • Then in such case the methods are called , overloaded. • Process is called method overloading • It is one of the way Java implements the polymorphism • Restriction is : the type or number of the parameters of each overloaded methods must differ. • It is not sufficient if they have different return types. • When an overloaded method is called, the version of the method whose parameters match the arguments is executed.
  • 14. 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 parameter:”+a +” and ”+b); return a+b; } } class OverloadDemo{ public static void main(String args[]){ Overload o=new Overload(); int result; o.ovlDemo(); o.ovlDemo(2); result=o.ovlDemo(4,6); System.out.println(“Result :”+result); } }
  • 15. void ovlDemo(int a) { System.out.println(“One parameter:”+a); } ---- int ovlDemo(int a) { System.out.println(“One parameter:”+a); return a*a; } Will throw an error, ie. Their return types are insufficient for performing overloading
  • 16. What is signature term used by java programmers? • A signature is the name of the method plus its parameter list • No two methods within the same class can have the same signature. • It does not include return type
  • 17. Overloading constructors • Constructors can also be overloaded like methods of a class class Myclass{ int x; Myclass(){ System.out.println(“Inside Myclass()); x=0; } Myclass(int i) { System.out.println(“Inside Myclass(int )); x=i; }
  • 18. 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; } }//end of Myclass
  • 19. class OverLoadConstructorDemo{ 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); } }
  • 20. • Output Inside Myclass() Inside Myclass(int) Inside Myclass(double) Inside Myclass(int,int) t1.x=0 t1.x=88 t1.x=17 t1.x=8
  • 21. Recursion • A method calling itself , this process is called recursion. • A method that calls itself is said to be recursive • The key component of a recursive method is a statement that executes a call by itself. • Eg: The factorial of a number until number N. • When a method calls itself , new local variables and parameters are allocated storage on the stack, the method code is executed with these new variables from the start. • A recursive call does not make a copy of the method.
  • 22. • Each recursive call returns, the old variables and parameters are removed from the stack and execution resumes at a point of call inside the method. • Recursive methods could be said to “telescope” out and back.
  • 23. A simple example of recursion class Factorial{ int factR(int n){ int result; if(n ==1) return 1; result=fact(n-1)*n; return result; } } //end of class factorial class Recursion{ public static void main(String args[]){ Factorial f= new Factorial (); System.out.println(“factorial of 3 is ”+f.factR(3)); System.out.println(“factorial of 4 is ”+f.factR(4)); System.out.println(“factorial of 5 is ”+f.factR(5)); }//end of main }// end of Recursion
  • 24. • Output: Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120 • When factR() function is called with an argument of 1, the method returns 1 otherwise it returns the product of factR(n-1)*n; • To evaluate this expression, the factR() is called with value n-1 • This process repeats until n equals 1 and the calls to the method begin running.
  • 25. • Recursive methods where there are in huge numbers, it will take a longer time to complete than iterative methods. • Too many recursive calls to a method could cause the stack to overrun • Storage of local variables and parameters are allocated in the stack, every time a call is made, it creates a new copy of these variables. There is possibility that stack can get exhausted. • If this happens, the java run time machine will cause an exception.
  • 26. Understanding static • When you want to define a class member that will be used independently of any object of that class, without any reference to a specific instance • To create such a member, precede its declaration with the keyword static. • When a member is declared as static, it can be accessed before any objects of its class are created. And without any reference to any object. • You can declare both the data variables and methods as static. • Common example for static is main() function.
  • 27. • main() is declared as static because it must be called by the JVM when your program begins. • Outside the class, to use a static member , you need to specify the name of the class followed by the dot operator • No objects has to be created. • If you assign the value 10 to a static variable called count that is part of Timer class, Timer.count=10; • Variables declared as static are essentially global variables • When an object is declared no copy of static variable is made • All instances of the class share the same static variable
  • 28. class StaticDemo{ int x; static int y; int sum(){ return x+y; } } class Sdemo{ public static void main(String args[]){ StaticDemo ob1=new StaticDemo(); StaticDemo ob2=new StaticDemo(); ob1.x=10; ob2.x=20; System.out.println(“of course, ob1.x and ob2.x are independent”); System.out.println(“ob1.x: ”+ob1.x+” “ +”ob2.x: ”+ob2.x); System.out.println(“Static variable y is shared”); StaticDemo.y=19; System.out.println(“Set StaticDemo.y to 19”); System.out.println(“ob1.sum:”+ob1.sum()); System.out.println(“ob2.sum:”+ob2.sum()); StaticDemo.y=100; System.out.println(“change StaticDemo.y to 100”); System.out.println(“ob1.sum:”+ob1.sum()); System.out.println(“ob2.sum:”+ob2.sum()); } }
  • 29. • Output Of course, ob1.x and ob2.x are independent ob1.x=10 ob2.x=20 Static variable y is shared. Set staticdemo.y to 19 ob1.sum():29 ob2.sum():39 Change staticDemo.y to 100 ob1.sum():110 ob2.sum():120
  • 30. • The difference between static method and normal method is that static method is called through its class name, without any object of that class being created. • Method declared as static have several restrictions – They can directly call only other static methods – They can directly access only static data – They do not have this reference. class StaticError{ int demon=3; // a normal instance variable static int val=1024; static int valDivDemon(){ return val/denom; //wont compile } }
  • 31. Static blocks • A class will require some type of initialization before it is ready to create objects. • Eg: establishing a connection to a remote site. • Java allows you to declare a static block • A static block is executed when the class is first loaded, hence it is executed before the class can be used for any other purpose
  • 32. class staticblock{ static double rootof2; static double rootof3; static{ System.out.println(“Inside the static block.”); rootof2=Math.sqrt(2.0); rootof3=Math.sqrt(3.0); } StaticBlock(String msg){ System.out.println(msg); } //end of staticblock class SDemo{ public static void main(String args[]){ StaticBlock ob=new StaticBlock(“Inside Constructor”); System.out.println(“SquareRo ot of 2 is:”+StaticBlock.rootof2); System.out.println(“SquareRo ot of 3 is:”+StaticBlock.rootof3); } //end of main }//end of staticblock
  • 33. • Output Inside static block Inside constructor Square root of 2 is 1.414213 Square root of 3 is 1.732050
  • 34. Introducing nested and inner classes • A class declared inside another class is called nested class. • A nested class does not exists independently of its enclosing class • Scope of nested class is bounded by its outer class. • A nested class that is declared directly within its enclosing class scope is a member of its enclosing class. • It is possible to declare a nested class that is local to a block. • There are two types of nested class : – Preceded by a static modifier – Those that are not preceded by static modifier
  • 35. • Inner class it has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of outer class • Inner class is used to provide a set of services that is used only by its enclosing class.
  • 36. class Outer{ int nums[]; Outer(int n[]){ nums=n; } void analyze(){ Inner inob=new Inner(); S.O.P(“min:”+inob.min()); S.O.P(“max”+inob.max()); S.O.P(“avg:”+inob.abg()); } } class Inner{ int min(){ int m=nums[0]; for(int i=1; i<nums.length;i++) if(nums[i]<m) m=nums[i]; return m; } int max(){ int m=nums[0]; for(int i=1; i<nums.length;i++) if(nums[i]>m) m=nums[i]; return m; } int avg(){ int a=0; for(int i=0;i<nums.length;i++) a+=nums[i]; return a/nums.length; } }
  • 37. class nestedClassDemo{ public static void main(String args[]){ int x[]={3,2,1,5,6,9,7,8}; Outer o=new Outer(x); o.analyze(); } } • Output mini:1 max:9 avg:5
  • 38. Varags: variable length arguements • Used when the number of argument list is not fixed in a method • For example: A method that opens an internet connection might take a user name, password , filename, protocol and so on, but supply defaults if some of this information is not provided. • Earlier two different ways it is handled, when maximum number of arguments was known, then you could overload version of the method, one for each way the method could be could. • Second approach , is to put all the arguments into an array and then array is passed into the method.
  • 39. • Both of these methods resulted in clumsy situations. • JDK 5 onwards, it included the feature that is simplified the creation of methods that require a variable number of arguments, called as varargs- variable length arguments. • A method that takes a variable number of is called variable-arity method or simply varargs method. • The parameter list for a varargs method is not fixed, but rather variable in length.
  • 40. Varargs basics • Variable length argument is specified by three periods (…) static void vaTest(int … v){ System.out.println(“Number of args:”+v.length); System.out.println(“Contents:”); for(int i=0;i<v.length;i++) System.out.println(“arg ”+i+”:”+v[i]); System.out.println(); } • Here vaTest() method can be called with zero or more arguments. • It causes v to be implicitly declared as an array of the type int []
  • 41. class Varargs{ static void vaTest(int … v){ System.out.println(“Number of args:”+v.length); System.out.println(“Contents:”); for(int i=0;i<v.length;i++) System.out.println(“arg ”+i+”:”+v[i]); System.out.println(); }//end of vaTest public static void main(String args[]){ vaTest(10); vaTest(1,2,3); vaTest(); }//end of main } //end of class
  • 42. • A method can have normal parameters along with the variable-length parameter • However the variable –length parameter must be last parameter declared by the method. • Eg: int doIt(int a,int b, int … vals){ } In this case if the function call should have first two parameters as int type, after two parameters it can have any type will be stored in vals.
  • 43. int doIT(int a, int b, double c,int … vals, double .. morevals) { .. } • The attempt to declare the second varargs parameters is illegal.
  • 44. Overloading Varargs Methods • You can overload a method that takes a variable-length argument • Following program overloads vaTest() three times. • Varargs can be overloaded in two ways • First , the types of its varag parameter can differ i.e. varTest(int … ) and vaTest(boolean …) • Second way is to add one or more normal parameters • vaTest(String msg, int … )
  • 45.
  • 46.
  • 47.
  • 48. Varargs and Ambiguity • It is possible to create an ambiguous to an overload varargs method. class varargs4{ static void vaTest(int … v){ // … } static void vaTest(boolean … v){ //… } public static void main(String args[]){ vaTest(1,2,3); vaTest(true, false,false); vaTest(); // lead to confusion } }
  • 49. static void vaTest(int … v) { // } static void vaTest(int n, int …v){ // } vaTest(1); // the compiler cannot resolve this kind of call, hence it will through an error.
  翻译: