class
Passing an object to a method example
With this example we are going to demonstrate how to pass an object to a method. In short, we have created a class and a method to pass the object of the class:
- We have created a class,
Character
with a char field. - We have created another class,
PassObject
, that has a static method,void setCh(Character y)
. The method gets aCharacter
object and changes its char field to'z'
. - We create a new instance of
Character
class and set its char field to'a'
. - Then we use the
setCh(Character y)
method ofPassObject
class to change again the field ofCharacter
object. - In both ways the field of Character object is changed.
Let’s take a look at the code snippet that follows:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | package com.javacodegeeks.snippets.core; class Character { char ch; } public class PassObject { static void setCh(Character y) { y.ch = 'z' ; } public static void main(String[] args) { Character x = new Character(); x.ch = 'a' ; System.out.println( "1: x.ch: " + x.ch); setCh(x); System.out.println( "2: x.ch: " + x.ch); } } |
Output:
1: x.ch: a
2: x.ch: z
This was an example of how to pass an object to a method in Java.