This exercise exercises the relationship between the car class and the factory class, and completes some output through calls between the methods.
Note the parameters and the settings for the return value.
1 PackageCom.cnblogs.java;2 3 Public classTestcar {4 Public Static voidMain (string[] args) {5Car c1=NewCar ();//instantiation of6 c1.info ();7C1.setname ("Bentley");8C1.setprice (1000000);9C1.wheel=4;Ten c1.info (); One AFAC f=NewFAC ();//Factory instantiation -Car C2=f.procar ();//the factory produces a new car called the C2 object, which is equivalent to initializing a car by invoking a method - F.descar (C2); the -Car C3=f.procar ("Rolls-Royce", 10000000, 4); - F.descar (C3); - + } - + } A //Factory class at classfac{ - //How to make a car: The function is to initialize a new car - PublicCar Procar () { - return NewCar ();//The equivalent of car c=new car (); Returns c after instantiation - } - //Heavy-duty method for manufacturing automobiles: Initializing a new car in PublicCar Procar (String N,intPintW) { -Car c=NewCar (); toC.name=N; +C.price=p; -C.wheel=W; the returnC//returns c after instantiation * } $ Public voidDescar (Car C1) {//which car is the description of the transfer parameter ?Panax NotoginsengC1.info ();//call the info () method to describe a car - } the } + A //Automobile class the classcar{ + //Properties -String name;//the brand of the car $ intPrice//the value of the car $ intWheel//Number of tires - //Method - Public voidinfo () { theSystem.out.println ("Brand of the car:" +name+ "Value:" +price+ "Number of tires:" +wheel); - }Wuyi PublicString GetName () {//get the brand of the car the returnname; - } Wu Public voidSetName (String N) {//set the brand of the car -Name=N; About } $ Public voidSetprice (intp) { -Price=p; - } - Public voidSetwheel (intW) { AWheel=W; + } the -}
Operation Result:
object creation and usage exercises