Object passing in Java
Give a simple example to illustrate
Requirement: enables you to get data from objects of the associated Car class by associating two classes with the person object
A person class, a Car class,
==> Person Class
class person{// Setting Variables private int pid; private string pname; private int page; private car carname; // Multi-Parameter construction method public person (string pname, int page) { this.setpname (pname); this.setpage (page); } public string getinfo () { return "Name: " + getpname () + "\ r" + "Age:" + getpage () + "\ r"; } public void setcarname (Car carname) { this.carname = carname; } public car getcarname () { return this.carname; } public void setpname (String pname) { This.pname = pname; } public string getpname () { return this.pname; } public void setpage (int page) { this.page = page; } Public int getpage () { return this.page; } }
car class
class car{ private string cname; private person pname; // Constructor public car (String CNAME) { this.setcname (CNAME); } public void setpname (Person pname) { this.pname = pname; } Public person getpname () { return this.pname; } public void setcname (String cname) { this.cname = cname; } public string getcname () { return this.cname;&Nbsp; } public string getcarinfo () { return "car Name:" + getcname (); }}
==> Test Class
public class Testdemo {public static void main (string[] args) {person p = new person ("Tom", 20); Car car = new car ("BMW");p. Setcarname (car); Car.setpname (P); System.out.println (P.getinfo ());//Gets the contents of its Car object through the Person object System.out.println (P.getcarname (). Getcarinfo ());//Through The Car object gets the contents of the Person Object System.out.println (Car.getpname (). Getpname ());}}
Object passing in Java