Through chestnuts, a man can have more than one car
Define people this class
People can have a lot of cars, class car properties with arrays
classperson{PrivateString name; PrivateString Phone; Privatecar[] Car; PublicPerson () {} PublicPerson (string name, String phone) { This. Name =name; This. Phone =phone; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString Getphone () {returnphone; } Public voidSetphone (String phone) { This. Phone =phone; } Publiccar[] Getcar () {returncar; } Public voidSetcar (car[] Car) { This. Car =car; } PublicString GetInfo () {return"Name" +name+ ", phone" +phone; }}
Then define the car class
classcar{PrivateString name; Private DoublePrice ; private person person; PublicCar () {} PublicCar (String name,DoublePrice ) { This. Name =name; This. Price =Price ; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public DoubleGetPrice () {returnPrice ; } Public voidSetprice (DoublePrice ) { This. Price =Price ; } PublicPerson Getperson () {returnPerson ; } Public voidSetperson (person person) { This. person =Person ; } PublicString GetInfo () {return"Brand:" +name+ "Price:" +Price ; }
Then, in the test class, each instance of the person class and the car class
Man, this object is only new.
Cars can be unlimited, here are symbolic examples of three
New Person ("a three", "33333333"); New Car ("BMW", 400000); New Car ("Bora", 100000); New Car ("Bao Chun", 800
After the object is instantiated, set up relationships with each other, i.e. one person corresponds to three cars, and each car corresponds to one person
Passing values by set method
P.setcar (new car[]{c1,c2,c3}); C1.setperson (p); C2.setperson (p); C3.setperson (p);
Test
Through people, check the vehicle information under it
System.out.println (P.getinfo () + "owned vehicle"); for (int i=0;i<p.getcar (). length;i++) { //array type print with For loop }
Run
Through the car, find the owner information
System.out.println (C1.getinfo () + "owner of this car:" +C1.getperson (). GetInfo ()); System.out.println (C2.getinfo ()+ "owner of this car:" +C1.getperson (). GetInfo ()); System.out.println (C3.getinfo ()+ "owner of this car:" +c1.getperson (). GetInfo ());
Run
A one-to-many mapping relationship in Java