Constructors. Constructors for zamovchuvannyam. Weekly constructors from other constructors. Need more constructors? What is a constructor in java

Golovna / Contacts

The constructor is a special method that calls the hour of the creation of a new object. Do not start manually initializing all changes of the class under the hour of creation of the first copy. Sometimes it’s simpler, so that the meaning was created for the mind at the hour of the creation of the object. Really, the constructor of the necessary automatic initialization of changes.

The constructor initializes the object without delay at the hour of creation. Ім'я constructor zbіgaєtsya with ім'ям class, including register, and the syntax of the constructor is similar to a method without a value, which turns.

Private int Cat(); / / This is how the method looks at the name Cat Cat (); // this is what the constructor of the Cat class looks like

On the view of the method, the constructor never turns anything.

The constructor designates the class, as the time of the creation of the object class, and the important part of the class. As a rule, programmers are prompted to specify a constructor. Since there is no explicit constructor, Java will automatically create yogo for the loopback. If we implemented the class box, then the same constructor was not created.

Dodamo up to the class constructor, which is easy to insert the initial values ​​for the box.

Class Box ( int width; // width of the box int height; // height of the box int depth; // depth of the box // Constructor Box() ( width = 10; height = 10; depth = 10; ) getVolume() ( return width * height * depth; ) )

Mi timchasovo removed the method setDim() she added a constructor. Let's see what we see:

Box catBox = new Box(); mInfoTextView.setText("BoxView:" + catBox.getVolume());

The program will show the volume of the box, although we did not set the annual expansion for it. Zavdyaki the designer, be it a box, what is going on, mother, if it is fixed, it will be fixed.

Obviously, you can reverse the method setDim()(div. article about the class) and insert your own dimensions for the box:

Box catBox = new Box(); // Set your own dimensions for the box catBox.setDim (10, 20, 30); mInfoTextView.setText("BoxView:" + catBox.getVolume());

Now you can be clear what if after the keyword new we write im'ya class with shackles, then we really call the constructor of the class.

Blame food - but on the other hand, when the class was created, the constructor was not created, however, the code newBox() pratsyuvav. Right in that if a constructor is not explicitly assigned, Java will create a constructor that will be tricked out. For this type of wine, just give us a change of zero values. If you have created a constructor, then the designer will not work for the zamovchuvannyam.

Like a method, a constructor can have arguments. Constructor arguments are passed object initialization parameters. For example, like a class catє constructor, which is taken as an argument, the number, which means the number of the cat, then the object cat will be arranged like this:

Cat Cat = New Cat(8); // Cat is 8 years old

Yakscho cat(int)є single class constructor, then the compiler does not allow the creation of objects cat be in some other way.

However, let's turn to the boxes for cats. The designer of our creations is not the same as the one who creates the same boxes. Create a constructor with class parameters box and comment out the first constructor without parameters:

// Another constructor Box(int ​​w, int h, int d) (width = w; height = h; depth = d;)

In order to replace a class with a single constructor with parameters, you will have to specify the default value when the class is empty:

// This constructor is now invalid // Box catBox = new Box(); // The constructor must specify the value of the box expansion Box catBox = new Box(100, 200, 100); mInfoTextView.setText("BoxView:" + catBox.getVolume());

Before speech, with such a constructor, the method setDim() we do not need. We can insert expanded boxes into the constructor. So the box has become better for everything and does not change its dimensions, then the method, perhaps, is zayviy. Ale, if we at least loosen the boxes, then the method will be overwhelmed.

The class may be the mother of a sprig of constructors. Know the comments of the first designer and create two boxes - a box for locking and a large box.

Box defaultBox = new Box(); mInfoTextView.setText("Standard Box Value: " + defaultBox.getVolume()); Box bigBox = new Box(100, 200, 200); mInfoTextView. append("\nAppend big box: " + bigBox.getVolume());

Tobto, Bachimo, that designers promote innovation, like methods.

For example, we can create one constructor specifically for the box in front of a cube, all sides are equal:

// Third constructor for the cube Box(int ​​len) (width = height = depth = len;)

Calculate the size of the cube:

Box cube = new Box(5); intvol = cube.getVolume(); mInfoTextView.setText("Cube View:" + vol);

Victory object as parameters

For the time being, we have worked as parameters in simple type constructors. Ale can pass the object to the class itself. Dodamo one more constructor:

// Wickbox object of type Box Box(Box ob) (width = ob.width; height = ob.height; depth = ob.depth; )

For code programs, you can speed up the constructor like this:

Box1 = new Box(100, 200, 100); Box cloneBox = new Box(box1); intvol = cloneBox.getVolume(); mInfoTextView.setText("Volume boxes:" + vol);

Class Box (outdoor)

packageuk.alexanderklimov.box; class Box ( int width; // width of the box int height; // height of the box int depth; // depth of the box // Constructor Box() ( width = 10; height = 10; depth = 10; ) // Another constructor Box( int w, int h, int d) (width = w; height = h; depth = d;) // Third constructor for the cube Box(int ​​len) (width = height = depth = len; ) 'ct to type Box Box(Box ob) (width = ob.width; height = ob.height; depth = ob.depth; ) // enumerable box obs int getVolume() ( return width * height * depth; ) // set box expander void setDim (int w, int h, int d) ( width = w; height = h; depth = d; ) )

Wiklik revantaging constructors via this()

To the right of the rehashed constructors, manually one constructor to click through the other one via the keyword this. When vikonnі designer this() the constructor is selected in order to change the options, which one is given to the list of parameters. Let's check out the operators that are in the middle of the output constructor, so that's how it works. Wiklik constructor this() may be the first operator in the constructor.

For the cob we create a class, which is not a designer this(), to understand the difference.

Class Cat (int age; int birthday; // Initialize explicitly change Cat(int i, int j) (age = i; birthday = j;) // Initialize one of these values ​​Cat(int i) (age = i; birthday = i; ) // Nadamo capturing value 0 Cat() ( age = 0; birthday = 0; ) )

We created a class from trioma by designers. We will rewrite the class, vikoristovuyuchi constructor this().

Class Cat( int age; int birthday; // Initialize explicitly changing Cat(int i, int j) ( age = i; birthday = j; ) // Initializing one of these values ​​Cat(int i) ( this(i, i);// call Cat(i, i);

We now have more than one constructor, which gives values ​​to the fields - Cat(int, int). What should be observed when the operator is victorious:

Cat Cat = New Cat(8);

Wiklik constructor cat(8) bring up the constructor this(8, 8), which is equivalent to the constructor's call Cat(8, 8).

What should be observed when the operator is victorious:

Cat cat2 = New Cat();

In which direction the constructor is called this(0) what to bring to the end of the designer cat(0) the same version of the constructor goes after the list of parameters. When constructor cat(0) essentially calling the constructor Cat(0, 0).

Conversion of Constructors via Constructor this() allows you to turn off the duplication of the code that changes the hour of class capture.

But let's keep it safe, because the designers, like calling the designer this();

close constructor

Other classes are created only by saving some static watering and static methods. It is customary to give names to such classes utilities but not obov'yazkovo. Such a class does not need a constructor, but if the author of the yoga class does not create it, the system itself will create a constructor for locking. Such a constructor is not a sensation, but it can also become a pardon. In order to defend against a similar problem, it is your own fault to create an empty constructor and close it.

Public class Utils ( private Utils() ( throw new AssertionError(); ) ... //Your correct code // Incorrect code, for demonstration purposes only! public static void someMethod()( Utils utils = new Utils(); toString( ); ) )

Row throw new AssertionError() not obov'yazkovoy, but it will help you to show a pardon, as if you call the designer from the very class. The compiler will skip this option, but the program will end with a pardon.

Utils.someMethod(); // the program will close with a pardon

You cannot create a subclass for this class.

I live! Today, we will consider an even more important topic about our objects. Here, without further ado, we can say that with the help of your knowledge you make a good day with a real robot! We'll talk about constructors.

You, perhaps, you can hear this term in the past, but in truth, being built by designers, just didn’t mention it myself :)

What kind of designers and stinks do you need now?

Let's take a look at two examples. public class Car ( String model; int maxSpeed; public static void main (String args) ( Car bugatti = new Car () ; bugatti. model = "Bugatti Veyron" ; bugatti. maxSpeed ​​= 407 ; ) ) We made our car and installed for the new model that maximum speed. However, the real project object Car will obviously not have 2 fields. And, for example, 16 waterings! public class Car (String model; // model int maxSpeed; //maximum speed//volume of engine// call of the Vlasnik// number of seats at the salon String salonMaterial; //material for the salon boolean insurance; // Chi is insured//country virobnik inttrunkVolume; // luggage cover int accelerationTo100km; public static void main (String args) ( Car bugatti = new Car () ; bugatti. color = "blue" ; bugatti. accelerationTo100km = 3 ; bugatti. engineVolume = 6.3 ; bugatti. manufacturerCountry = "Italy" ; bugatti. Amigo" ; bugatti.yearOfIssue = 2016 ; bugatti.insurance = true ; bugatti.price = 2000000 ; bugatti.isNew = false ; bugatti.placesInTheSalon = 2 ; bugatti.max ; We have created a new Car object. One problem: we had 16 waterings, but we had less than 12 waterings! Try for the code to know tі, yakі mi zabuli! Not so easy, right? In such a situation, the programmer can easily be merciful and miss the initialization of this field. As a result, the behavior of the program will become pardonable: public class Car (String model; // model int maxSpeed; //maximum speed int wheels; //disk width double engineVolume; //volume of engine Stringcolor; //Colour int yearOfIssue; // Rick release String ownerFirstName; //Vlasnik's name String ownerLastName; // call of the Vlasnik long price; //price boolean isNew; //Nova chi nі int placesInTheSalon; // number of seats at the salon String salonMaterial; //material for the salon boolean insurance; // Chi is insured String manufacturerCountry; //country virobnik inttrunkVolume; // luggage cover int accelerationTo100km; //roll up to 100 km/year in seconds public static void main (String args) ( Car bugatti = new Car () ; bugatti. color = "blue" ; bugatti. accelerationTo100km = 3 ; bugatti. engineVolume = 6.3 ; bugatti. manufacturerCountry = "Italy" ; bugatti. Amigo" ; bugatti.yearOfIssue = 2016; bugatti.insurance = true; bugatti.price = 2000000; bugatti.isNew = false; bugatti.placesInTheSalon = 2; bugatti.max Ve = 47 "Model Bugatti Veyron. Engine volume - "+ Bugatti. engineVolume+", trunk -"+bugatti. trunkVolume+ ", Salon of crushings"+ Bugatti. salonMaterial + ", disk width -"+ Bugatti. wheels + ". Bula pridbana at 2018 rotsi panom"+ Bugatti. ownerLastName); ) ) Viewing in the console: Model Bugatti Veyron. Engine volume - 6.3, luggage compartment - 0, interior damages null, disc width - 0. Your buyer, who has given 2 million dollars for a car, is clearly not worthy of what they called yoga “ pan null”! And even more seriously, the results in our program showed incorrect creations of objects - a car with a disk width of 0 (so it went without disks), a full trunk, a salon, a broken one from an unknown material, that is, a comus, that it is unreasonable to lie. You can only show, like such a pardon, you can "wistrily" under the hour of the robot program! We need to get rid of such situations. It was necessary for our program to have an exchange: when creating a new machine object for a new zavzhdi owing to buti indicated, for example, the model and the maximum speed. Otherwise - do not allow the creation of the object. Zim zavdannyam easy to handle constructor functions. The stinks took their name wrong. The designer creates his own "framework" for the class, for which a new object to the class can be confirmed. Let's turn for clarity to the simplest version of the Car class with two fields. With our improvements, the constructor for the Car class will look like this: public Car (String model, int maxSpeed) ( this . model = model; this . maxSpeed ​​= maxSpeed; ) And the object creation now looks like this: public static void main (String args ) ( Car bugatti = new Car ( " Bugatti Veyron " , 407 ) ; ) how the constructor is created. Vіn is similar to the natural method, but it has no type of value to turn. If so, in the constructor it is indicated the name of the class, also the great letter. Our vipadka has Car. In addition, the designers have victorious new things for you. this. "this" in English - "tsey, tsyogo". The whole word is about a specific subject. The code for the constructor: public Car (String model, int maxSpeed) (this. model = model; this. constructor. maxSpeed ​​for the desired car (how we do it) = the maxSpeed ​​argument, which is the constructor's instructions. "So it happened : public class Car (String model; int maxSpeed; public Car (String model, int maxSpeed) (this.model=model;this.maxSpeed=maxSpeed;)) Car ( " Bugatti Veyron " , 407 ) ; System.out.println (bugatti. model) ; System. Bugatti Veyron 407 The constructor has successfully pressed the required values. You, perhaps, remembering that the constructor already guesses the best method! So it’s just the same: the constructor is the same method, only a few specific ones :) So the same as the method, our constructor passed the parameters. And just like the viklik method, the constructor viklik is not spliced, because you can't specify them: public class Car (String model; int maxSpeed; public Car (String model, int maxSpeed) (this. Public static void main (String args) (Car bugatti = new Car(); //pardon!)) Bachesh, the constructor has created those that we tried to reach. Now you can't build a car without the firmware of your model! can change. Reveal that 2 cats live in your house. I took one of them for a koshenko, and the other I brought home from the streets already grown up and you don’t know exactly how old you are. So, our program is obliged to create cats of two kinds - with them for the first cat, and only with them - for another cat. For whom we can change the constructor: public class Cat (String name; int age; //for the first cat //For another cat public Cat (String name) ( this . name = name; ) public static void main (String args) ( Cat barsik = new Cat ("Barsik" , 5 ) ; Cat streetCatNamedBob = new Cat ( "Bob" ) ; ) ) We gave the constructor with the parameters "im'ya" and "vіk" one more, only z im'yam. So we ourselves changed the methods in the past lessons. Now we can successfully create offensive options for cats :)

Remember, at the beginning of the lecture, we were told that you were already chivalrous as designers, but didn’t mention whom yourself? So i є. Right in what the skin class in Java has so titles designer for locking. No one has any reasonable arguments, but vin spratsovuє shorazu pіd the hour of the creation of any object of any class. At first glance, it is unremarkable. Well, they created an object and created it, where is the designer's robot here? For fun, let's just write an empty constructor for the Cat class, and in the middle of the new one, we'll type a phrase into the console. If it looks like it won't, then the constructor is out. public class Cat ( public Cat () ( System. out. println ("Created a cat!" ) ; ) public static void main (String args) ( Cat smears = new Cat () ; // Axis here spratsyuvav constructor for zamovchuvannyam } } View to console: Made a cat! Axis and confirmation! Behind the locks, the designer is always invisibly present in your classes. But you need to know one particular thing. The default constructor is derived from the class if you create such a constructor from the arguments. The proof of which is true was already more abundant. What code y axis: public class Cat (String name; int age; public Cat (String name, int age) (this.name = name; this.age = age;)) new Cat () ; //pardon! ) ) We couldn't create a cat without a name, so we assigned a constructor for Cat: row + number. Default constructor as soon as possible sign from class. For this, obov'yazkovo remember: as if your class needs a sprig of designers, including empty, it is necessary to create yoga. For example, we are creating a program for a veterinary clinic. Our clinic would like to do a good job of helping homeless cats, we don't know their names about them, ever. Then our code might look like this: public class Cat (String name; int age; //for domestic cats Public Cat (String name, int age) ( this . name = name; this . age = age; ) //for outdoor cats public Cat () ( ) public static void main (String args) ( Cat barsik = new Cat ( " Barsik " , 5 ) ; Cat streetCat = new Cat () ; ) ) create cats of both types :) For a constructor (like a method), the order of the arguments is important. We remember our constructor's arguments of the name and age of missions. public class Cat (String name; int age; public Cat (int age, String name) ( this . name = name; this . age = age; ) public static void main (String args) ( Cat barsik = new Cat ("Barsik ", 10); // Pardon!)) Pardon! The constructor clearly describes: when the Cat object is created, you can be passed number that row, itself in that order. That's why our code doesn't work. Ob'yazkovo zapom'yat tse and vrahuy when concatenating your own classes: public Cat (String name, int age) (this.name = name; this.age = age;) public Cat (int age, String name) (this. age = age; this .name = name;) There are two completely different constructors! Yakshto vyslovit in one rechenni vіdpovіd on zapitanya "Navischo need a constructor?", you can say: in order for the objects to be known in the right place. If you win constructors, all your changes will be correctly predicted, and there will be no machines with a default code and other incorrect objects in the program. Їхнє vikoristannya is also a guide for us for the programmer himself. Yakshcho іnіtsіalіzuvatimesh fields independently, the great risk to miss and have mercy. But this will not be the case with the constructor: if you pass not all the necessary arguments from the new one, or if you mix up their types, the compiler will immediately issue a pardon. Okremo varto tell me about those who inside the constructor do not place the logic of your programs. For whom do you have orders methods, In which you can describe all the functionality you need. Let's see why the logic in the constructor is such a bad idea: public class CarFactory (String name; int age; int carsCount; this .carsCount = carsCount;System.out.println ( "Vona bula founded" "The average won't vibrate"+ (this . carsCount / this . age) + "Cars on the river"); ) public static void main ( String args ) ( CarFactory ford = new CarFactory, which describes the factory for the production of cars Use the constructor and initialize all the fields, and use the logic here: display information about the factory in the console. It would have been given - there is nothing nasty in it, the program worked miraculously. View to console: Our car factory is called Ford Vaughn and was founded 115 years ago. During the whole hour, 50,000,000 cars were driven on it. Ale, in truth, they laid down a mine of improved diy. I similar code can even easily cause pardons. Apparently, now we are talking not about Ford, but about the new factory "Amigo Motors", which is less likely to happen and produce 1000 cars: public class CarFactory (String name; int age; int carsCount; age, int carsCount) (this. name = name; this.age = age; this.carsCount = carsCount;system.out.println( "Our car factory is called"+ this . name); System. out. println( "Vona bula founded"+ this . age + "the fate of that"); System. out. println( "For the whole hour, it was ruined"+ this . carsCount + "cars"); System. out. println( "The average won't vibrate"+ (this . carsCount / this . age) + "Cars on the river"); ) public static void main (String args) ( CarFactory ford = new CarFactory ( " Amigo Motors " , 0 , 1000 ) ; ) ) Wisnovok to the console: Our car factory is called Amigo Motors Exception in thread "main" java.lang.ArithmeticException: / by zero Vaughn was founded 0 years ago In the last hour, 1000 cars were generated at CarFactory. (CarFactory.java:15) at CarFactory.main(CarFactory.java:23) Process finished with exit code 1 We've arrived! The program ended with an unreasonable pardon. Try to guess what is the reason? The reason is in the logic, as we have placed in the constructor. And itself - the y-axis of this row: System. out. println( "The average won't vibrate"+ (this . carsCount / this . age) + "Cars on the river"); Here we are counting and diluting the number of vibrating machines per factory. And our factory’s chips are new (tobto їy 0 rokіv) - the result has been subdivided by 0, which is blocked by mathematics. As a result, the program ends with a pity milk. How can we bring warto bulo? Blame all the logic in a single method and call it, for example, printFactoryInfo() . As a parameter, you can pass a CarFactory object. There you can put all the logic, and at the same time - the processing of possible pardons, for the sake of ours, with zero fate. To the skin. The constructors of the necessary correct task will become an object. For business logic, we can use methods. Do not varto zmishuvati one with one. The axis of the kіlka korishnye silan, you can read more about the constructors:

The constructor is a structure similar to the method, which is recognized as belonging to the created instance of the class. Designer characteristics:
  • The name of the designer can be matched to the name of the class (for housekeeping, the first letter is great, call the name);
  • Constructor є have be-yakom class. They didn't write anything yet, the Java compiler itself will create a standard constructor (default constructor), which will be empty and will not hurt anything, just a wiki of the superclass constructor.
  • A constructor similar to a method, but not a method, is not respected by a member of the class. For this reason, yoga cannot be degraded and redefined in the subclass;
  • Constructors do not decline;
  • Constructors can be cheap in the class. І here the constructors are called revantations;
  • Even if the constructor is not declared in the class, the compiler will automatically add the constructor code without parameters;
  • A constructor cannot be typecast, it can be type void , so void type is cast, instead of being a constructor but a method, instead of the class name.
  • The constructor is allowed a return statement, but only empty, without any meaning to turn;
  • The constructor is allowed to set access modifiers, you can set one of the modifiers: public, protected, private, or without a modifier.
  • The constructor cannot be the mother of abstract, final, native, static modifiers or synchronized;
  • The key word of which one is applied to another constructor in this class. If it is victorious, then the beast may be the first row of the designer;
  • The keyword super is a call to the constructor of the Batkiv class. Yakshcho vikoristovuєtsya, until new May be the first row of the designer;
  • If the constructor does not write the super constructor's query to the ancestor class (with or without arguments), the compiler automatically appends code to the ancestor class's constructor's query without arguments;

Constructor for locking

Constructor є have be-yakom class. For example, they didn’t write anything, the Java compiler itself creates a constructor for the lock (default constructor). This constructor is empty and do nothing, krim vikliku superclass constructor. Tobto. to write: public class Example () it is equivalent to writing: public class Example (Example() (super;)) This type does not explicitly specify an ancestor class, and behind the hook, all Java classes degrade the Object class, so the constructor of the Object class is invoked. If a class has been assigned a constructor with parameters, and there is no overridden constructor without parameters, then a constructor without parameters has a pardon. Tim is no less, Java, starting from version 1.5, you can tweak constructors with changeable arguments. If you are a designer, if you have an argument for change, then the designer’s call for promotion will not be pardoned. It will not be that the argument of the change of life can be allowed. For example, the next butt cannot be compiled, just comment the constructor with the argument of the change date, then the compilation and launch will be successful and as a result of the work in the line with the DefaultDemo code dd = new DefaultDemo() ; Call the constructor DefaultDemo (int ... v). Naturally, in which way it is necessary to speed up JSDK 1.5. File DefaultDemo.java class DefaultDemo ( DefaultDemo (String s) ( System. out. print ("DefaultDemo(String)" ) ; ) /* DefaultDemo(int ... v) ( System.out.println("DefaultDemo(int ...)"); ) */ public static void main (String args ) ( DefaultDemo dd = new DefaultDemo () ; ) ) The output of the program when the constructor is uncommented is: DefaultDemo (int . . . ) constructor (without parametrіv) will be an obov'yazkovym yavisch, oskіlki pіdstanovka constructor for zamovchuvannyam vіdbuvaetsya automatically.

Under the hour of the creation of the object, they are sequentially counted as follows:
  • Shukaetsya class of the object of the middle classes, which already vikoristovuyutsya in the program. There is no way to do that, you can search all available program directories and libraries. After the class is shown in the catalog, or the libraries are shown the creation and initialization of static fields of the class. Tobto. for skin class, static fields are initialized only once.
  • You can see the memory of the object.
  • The initialization of the watering of the class is victorious.
  • Vіdpratsovuє class constructor.
  • A message is being formed on creations and initializations of objects. Tse i є znachennym vyslovlyuvannya, scho I create an object. The object can be created for the help wiki to the newInstance() method of the java.lang.Class class. And here the constructor without a list of parameters is victorious.

Changeover of designers

Constructors of the same class can have the same name and signature. Such power is called overloading. If there is a class of designers, then there is a change of designers.

Parameterized constructors

The constructor's signature is the list of types of parameters, and the sequence of their types in the list of parameters of the constructor. The type of result that turns out is not guaranteed. The constructor does not rotate the same parameters. I explain the situation at the sensi, as Java separates the permutation of constructors and methods. Java distinguishes between revantation methods not by the type that is being rotated, but by the number, types, and sequence of types of input parameters. A constructor can't convert to a void type, otherwise it can transform into a generic method, regardless of the similarity with the class name. The stepping butt is shown. File VoidDemo.java class VoidDemo ( /** * This constructor */ VoidDemo () ( System. out. println ("Constructor" ) ; ) void VoidDemo () ( System. out. println ("Method" ) ; ) ) ) without parametrіv, scho turn. Tim is not less, for the constructor you can set one of the three modifiers public, private or protected. The butt now looks like this: File VoidDemo2.java class VoidDemo2 ( /** * This constructor */ public VoidDemo2() ( System.out.println("Constructor" ) ; ) /** * But it's the same as the original method, don't be surprised by the similarity * to the class name, but the void type */ private void VoidDemo2 () ( System. out. println ("Method" ) ; ) The constructor is allowed to write a return statement, but only empty, without the desired value to turn. File ReturnDemo.java class ReturnDemo( /** * The constructor allows the *return statement to be used without parameters. */ public ReturnDemo() ( System.out.println("Constructor" ) ; return ; ) public static void main(String s )

Constructors parameterized by change-domain arguments

Java SDK 1.5 introduced an additional tool - variable length arguments for constructors and methods (variable-length arguments). Until the last change, the number of documents was processed by two non-manual methods. The first letter of repayment for those who have the maximum number of arguments is surrounded by a small number and a distant view of the house. In such a way, it is possible to create versions of the method that are changed, one per variant of the list are passed to the argument method. Another way of re-insurance in the absence of a distant leg and a great number of arguments. And here the arguments were placed in an array, and the array was passed to the method. Arguments of the change in the future are mostly behind the offensive manipulations from the initial changes. The number of decimals from the validation arguments of the constructor is manually replaced by the method with the values ​​for the promotion. The argument of change is an array, and it is processed like an array. For example, the constructor for the Checking class with a changed number of arguments will look like this: will be stored in an array, the value set on the yak will be stored in a changed n. The constructor can call with a different number of arguments, including every day. Arguments are automatically stored in an array and passed through n. The difference between the number of arguments and the value of the array is equal to 0. Before the list of parameters in the order of the arguments of the changed value, there may be some language parameters included. For this type of parameter, which avenges the change in the number of arguments, it is the responsibility of the language remaining in the list of parameters. For example: class Checking (public Checking (String s, int ... n) ()) The list of parameters can only have one change value parameter. Due to the presence of two parameters in a change, the compiler cannot be deduced, one parameter ends and the other one starts. For example: class Checking (public Checking (String s, int . . n, double . . . d) // CARE! ( ) ) File Checking.java de pobuvav leather іz avtomobilіv per day. It is necessary from the main mass of fixed cars to choose those, like during the day they visited two task squares, say 22 and 15, from the map of the city. It is quite natural that a car can spend a day in rich squares, or maybe only one. It is obvious that the number of windows of squares is surrounded by the physical portability of the car. We will create a small program, the class constructor will accept it as an argument for the car number as an obov'yazkovy parameter and the numbers of the given squares of the space, the number of which can be changed. The constructor is reverified, if the car does not show up at two squares, if it shows up, then enter your number on the screen.

Passing parameters to a constructor

Moves have two types of parameters:
  • main types (primitives);
  • sending to objects.
The term call by value means that the constructor takes the value passed to it by the module to call. Contrary to this, call by reference means that the constructor removes the module type, which it calls to, the address of the change. Mov Java has more than one click per value. For the value of the parameter and the value of the setting of the parameter. Java doesn't swear by the community for requests for objects (if you want a lot of programmers and authors of some books, you won't be able to). Parameters for transferring objects in Java are disabled not by request, a for the values ​​sent to the object! For whatever reason, the constructor will take a copy of the value of all parameters. The constructor cannot work with its own input parameters:
  • the constructor cannot change the values ​​of input parameters in the main (primitive) types;
  • the constructor is impossible to change the force of the input parameters;
  • the constructor cannot be reassigned by setting input parameters to new objects.
The constructor can work with its own input parameters:
  • change the object's stan, which is transmitted as an input parameter.
It is a good idea to make sure that Java input parameters for the constructor are passed for the values ​​sent to the object. Also, for this application, it was added that the designer cannot change the setting of the input parameters, but actually change the use of copies of the input parameters. File Empoyee.java class Employee ( Employee (String x, String y) ( String temp = x; x = y; y = temp; ) public static void main (String args ) ( String name1 = new String ("Alice" ) ; String name2 = New String("Mary") ;Employee a = New Employee(name1, name2) ;System.out.println("name1=" + name1) ; System.) The result of seeing the program: name1= Alice name2= Mary Yakby in my Java object passing objects as parameters in vicoristovy vyklik for the request, then the constructor remembering in this application the name1 and name2 . In fact, the constructor cannot be replaced by the objects of the force, which are saved in the changed name1 and name2. It is worth noting that the parameters of the constructor are initialized with copies of these messages. Then the designer will change the copy space. Upon completion of the constructor's work, x and y are changed, and the last changes of name1 and name2 continue to work on the number of objects.

Parameter changes that are passed to the constructor.

The constructor cannot modify the passed basic type parameters. However, the constructor can modify the object that is being passed as a parameter. For example, consider this program: File Salary1.java class Salary1 (Salary1 (int x) (x = x * 3; System. out. println ("x="+x);)) public static void main (String args) ( int value = 1000 ; Salary1 s1 = new Salary1 (value) ; System. The result of seeing the program: x= 3000 value= 1000 Obviously, this method does not change the parameter of the main type. Therefore, after the constructor's call, the value of the change value is equal to 1000. In fact, there are three numbers:
  1. Change x is initialized with a copy of the value of the value parameter (that is, the number 1000).
  2. The value of the change x is built - now it will be 3000. However, the value of the change value will be equal to 1000.
  3. The constructor completes his work and changes x no longer wins.
At the offensive butt, the salary of the spіvrobіtnik is successfully built up, the shards are passed as a parameter to the method, the value of the object being sent. File Salary2.java class Salary2 ( int value = 1000 ; Salary2 () ( ) Salary2 (Salary2 x) ( x. value = x. value * 3 ; ) public static void main (String args ) Salary2 s2 = New Salary2 (s1) System."s1.value="(!LANG:+ s1.value); System.out.println("s2.value="+ s2. value); ) The result of seeing the program: s1. value=3000 s2. value= 1000'єкт. За виконання рядка Salary2 s2 = new Salary2(s1) ; конструктору Salary2(Salary x) передасться значення посилання об'єкт змінної s1 , і конструктор фактично потроїть зарплату для s1.value , оскільки копія (Salary x) , створювана всередині конструктора свідчить про об'єкт змінної s1 . !}

Constructors are parametrized by primitives.

Also, the parameters of the overridden constructor have a primitive that can sound (for example, int<- double), то вызов метода со суженным значением возможен, несмотря на то, что метода, перегруженного с таким параметром нет. Например: Файл Primitive.java class Primitive { Primitive (double d) { d = d + 10 ; System. out. println (!}"d=" + d) ; } public static void main (String args ) { int i = 20 ; Primitive s1 = new Primitive (i) ; } } The result of seeing the program: d= 30.0 Irrespective of those that have a daily constructor in the Primitive class, which may have a parameter of type int , the constructor with the input parameter double . Before the constructor call, change i will be expanded from type int to double. The reverse option, if i was changed to type double, and the constructor was bits with an int parameter, in this situation, calling bi to the mercy of compilation.

Weekly constructor and operator new

The constructor is always called with the new operator. When a constructor is called with the new operator, the constructor starts a form that is sent to a new object. Primusity constructor to form a replacement for a new object, it is not possible to send a request for a basic object, it is possible to create an object that can be deserialized. And with the new operator, it is not possible to formulate a replacement for a new object. For example: File Salary3.java class Salary3 ( int value = 1000 ; Salary3 () ( ) Salary3 (Salary3 x) ( x. value = x. value * 3 ; ) public static void main (String args ) ( Salary3 s1 = new Salary3 () ; System. out. println ("First object creation: " + s1. value) ; out. println (+ s1. value) ; Salary3 s3 = new Salary3 (s1) ; System. "What"s happend with first object?:"+ s1. value); ) The result of seeing the program: First object creation: 1000 Second object creation: 1000 What's happend with first object? : 3000 Third object creation: 1000 What's happend with first object? : 9000 Cob for extra row Salary3 s1 = new Salary3() ; a new object is created. Dali, just for the help of the row Salary3 s2 = new Salary3(s1) ; or rows Salary3 s3 = New Salary3(s1) ; If you can create a reference to an already known object, then s1.value s2.value and s3.value would take the same value 1000 . Really row Salary3 s2 = new Salary3(s1) ; create a new object for change s2 and change the object's state for change s1 by passing its value sent to the object, in the constructor parameters. At whom everything can be perekonatisya for the results of the output. And pіd h vykonannya row Salary3 s3 = new Salary3(s1) ; create a NEW object for the change s3 and change the object's camp for the change s1 again.

Constructors and initialization blocks

In the distribution of the creation of the object and the designers of the refurbishment of the wild character, as if it were viroblyayutsya at the hour of the creation of the object. Among them are the processes of initialization of the class and the implementation of the class constructor, as well as the internal order:
  1. All data fields are initialized with their own values, passed for promotion (0, false or null).
  2. The initiators of all waterings and the initiation blocks are winked in the order of their resurfacing in the voiced class.
  3. If the next constructor is called to the first row of the constructor, then the calling constructor is called.
  4. The body of the designer is victorious.
The constructor can be extended to initialization, but Java has three ways to initialize a field in a class:
  • assign the value in voiceless;
  • assign a value in the initialization block;
  • set a value for the constructor.
Obviously, it is necessary to organize the initialization code in such a way that it would be easy for someone to get it. As an example, an offensive class is introduced: class Initialization ( int i; short z = 10 ; static int x; static float y; static ( x = 2000 ; y = 3.141 ; ) Initialization () ( System. out. println ("i= " + i) ; System. out. println ("z=" + z) ; z = 20 ; ініціалізуються статичні змінні x та y значеннями за умовчанням. Далі виконується статичний блок ініціалізації. Потім проводиться ініціалізація змінної i значенням за умовчанням та ініціалізується змінна z Then the constructor enters the robot.

Constructors and decline

Designers don't give up. For example: public class Example ( Example () ( ) public void sayHi () ( system. out. println ("Hi" ) ; ) ) public class SubClass extends Example ( ) The SubClass class automatically degrades the sayHi () method from the parent class. At the same time, the constructor Example() of the father's class is not degraded by the SubClass header.

The this keyword in constructors

Constructors win over to refer to another constructor in the same class, but also with a different list of parameters. Even if the constructor has the this keyword, it can be in the first row, ignoring that rule until the compiler forgives. For example: File ThisDemo.java public class ThisDemo ( String name; ThisDemo (String s) ( name = s; System. out. println (name) ; ) ThisDemo () ( this ("John" ) ; ) public static void main ( String args ) ( ThisDemo td1 = new ThisDemo ( " Mary " ) ; ThisDemo td2 = new ThisDemo () ; ) ) The result of seeing the program: Mary John The first row is taken as an argument. The other one doesn't take away any arguments, he just calls out the first designer named "John" for the lock. In this way, you can, for the help of designers, set the values ​​of the fields explicitly and for locking, which is often needed in programs.

The super keyword in constructors

Constructors vikoristovuyut super, sob viklikati constructor superclass. Like the constructor vikoristovu super , this week is guilty of being in the first row, otherwise the compiler will see a pardon. Below is an example: File SuperClassDemo.java public class SuperClassDemo ( SuperClassDemo () ( ) ) class Child extends SuperClassDemo ( Child () ( super () ; ) ) class SuperClassDemo, in addition to the class Child. Oskilki super is responsible for being the first operator to win in the constructor of the subclass, whose order must always be the same and not fall into the fact that super() wins. If the wine is not victorious, then it will be victoriously awarded for locking the constructor (without parameters) of the skin superclass, starting from the base class. The next program will demonstrate when constructors are called. Call.java file //Create superclass A class A ( A ( ) ( System. out. println ( " Inside A constructor . " ) ; ) ) //Create subclass B that extends class A class B extends A(B()(System.out.println("Inside B constructor.");)) //Create a class (C) that expands the class class C extends B ( C ( ) ( System. out. println ( " Inside C constructor . " ) ; ) ) class Call ( public static void main ( String args ) ( C c = new C ( ) ; ) ) Visnovok tsієї programs: Inside A constructor. Inside B constructor. Inside C constructor. Constructors are called in the order of subordering of classes. Tshomu has a singing sense. Oskilki superclass do not have any knowledge about the subclass, then be it an initial, if you need vikonati, I will be okremoyu. According to the ability, she is guilty of changing her mind, whether it be an initial initiation, as a way to win a subclass. That’s why it’s the fault of vikonuvatisya first.

Constructors that are configured

The mechanism for identifying type pid hour vykonannya is one of the hardest basic principles of the Java movie that implements polymorphism. However, such a mechanism does not insure the retailer of an insane reduction of types in a number of varieties. The most common way is the manipulation of a group of objects, different types of such distant places are unknown, and they are determined at the hour of the meeting. Shards of a pardon, connected with the inconsistency of types, can appear only at the stage of vikonanny, which complicates their search and liquidation. The introduction of types that are configured in Java 2 5.0 often vindicate such pardons from the compilation stage and ensure the lack of type security. Explicitly cast types are required to transition from type Object to a specific type. Follow the mother in uvazі, scho nalashtuvannya types practice only with objects and do not expand on primitive types of data, so lie pose behind a tree of falling classes. Zavdyaki types that are tuned in, all given are automatically set and attached. This allows you to be safe in case of inconsistency of types and more often to beat the code again. Tipi, which are tuned, can be tweaked in the constructors. Constructors can be configured, navit as their class is not the type to be configured. For example: class GenConstructor (private double val;< T extends Number >GenConstructor (T arg) ( val = arg. doubleValue () ; ) void printValue () ( System. out. println ("val: " + val) ; ) ) class = new GenConstructor (100 ) ;GenConstructor gc2 = new GenConstructor ( 123.5F ) ;gc1.printValue() ;gc2.printValue() ; viklikati z be it
1. Understanding the designer

Constructor for locking - not a constructor, which does not have parameters. The designer behind the lock can be stunned by the class in an obvious rank, or it can be generated automatically.

In the most extreme way, for the ClassName class, the constructor behind the lock may look like this:

class ClassName(... // constructor null ClassName() ( // Body of the constructor // ... } ... }
2. In some cases, the constructor for locking is generated automatically in the class, but in some cases it is not? Butt

If you don't bare the same constructor in the class, then the constructor will be generated by locking. Therefore, the constructor for locking is generated in the class automatically less in that case, as the class does not avenge the implementation of other constructors. In order to replace the implementation of a class, if you want one constructor with parameters, then in order to voice the constructor behind the lock, it is necessary to voice it in the class with an explicit rank.

For example. For the attacking stunned class, the constructor for the locking is generated automatically

class CMyClass( int d; int GetD() ( return d; ) void SetD( int nd) (d = nd;))

Hovering a higher code means that it is possible to cast an object to a class with a different constructor for hinting:

// work, because the class doesn't have the same constructor anymore CMyClass mc = new CMyClass();

If you want to add one more constructor to the body of CMyClass (for example, a constructor with one parameter), then the constructor behind the lock will not be automatically generated

class CMyClass( int d; // the constructor behind the lock is not generated automatically CMyClass( int nd) (d = nd;) int GetD() ( return d; ) void Set( int nd) (d = nd;))

After the introduction of a higher implementation of the object, the designer's choice for locking is not to go. Prote, you can name an object from a variable constructor with one parameter

// compilation pardon, class snippets already voiced another constructor // CMyClass mc = New CMyClass(); CMyClass mc2= new CMyClass(7); // and this code works

As a result of the victorious row, you will see a pardon of the compilation:

The constructor CMyClass() is undefined

In order to implement the implementation of the constructor for the abbreviation and deafen the object of the class with the variant of the constructor for the abbreviation, it is necessary to put it explicitly. Tse mozhe buti, for example, so

class CMyClass( int d; // explicit constructor override CMyClass() ( d = 0; ) // null constructor with 1 parameter, CMyClass( int nd) (d = nd;) int GetD() ( return d; ) void Set( int nd) (d = nd;))

After such an implementation, it is possible to create an instance of the class with the variant of two constructors, for example

CMyClass mc = new CMyClass(); // call the constructor for the lock mc.d = 25; CMyClass mc2= new CMyClass(5); // Call constructor with 1 parameter

3. Wiklik of designers from other designers. Butt

The Java language language allows you to call a constructor class from another class constructor. For which vicariously the keyword this is used, for example, we refer to the inline class.

butt. At the butt, there is a display of the CPixel class, which implements a pixel on the monitor screen.

// Class, which implements a pixel on the monitor screen public class CPixel( // internal class changes private int x, y; // pixel coordinates private int color; // pixel color // constructor without parameters (by locking the constructor) CPixel() ( x = y = color = 0; ) // constructor with 2 parameters to initialize the coordinates CPixel( int _x, int _y) ( x = _x; y = _y; color = 0; ) // constructor with 1 parameter, which initializes only color CPixel( int _color) ( color = _color; x = y = 0; ) // constructor with 3 parameters, which call constructor with 2 parameters CPixel( int _x, int _y, int _color) ( // Constructor's callout with 2 parameters: binding first operation and only once this(_x, _y); //this(_color); // Reweek the constructor harrowed this.color = _color; // so you can) // access methods int GetX() ( return x; ) int GetY() ( return y; ) int GetColor() ( return color; )

Affiliation to the CPixel class in other program code (methods)

CPixel cp1= new CPixel(2,8); // Constructor tweet with 2 parameters CPixel cp2= new CPixel(3,5,8); // Constructor name, which name is another constructor int d; d = cp1.GetX(); // d = 2 d = cp2. getcolor(); // d = 8 d = cp2. GetY(); // d=5...

4. What kind of objects (wimogs) are superimposed on the call of other constructors from the constructor class?

In order to correctly call other constructors from the constructor class, it is necessary to add such symbols (restriction):

  • There can be at least one other constructor per class. Viklikati two and more other designers of the same class were fenced. It's logical that a constructor assigns an assignment to an object to a class only once (and not twice or more times);
  • The call of another constructor is due to the first operation in the constructor that is called. If the constructor of another constructor implements another (third, etc.) operation, then the compiler will see a pardon.

The most important function of any class is the constructor. Win allows you to create an instance of an object. If you don’t have a constructor, then the constructor is created for the lock:

Public class User(
int age;//field
String firstName;//field
String lastName;//field
User() (// the axis looks like this constructor behind the lock
// empty
}
}

How could you remember the constructor tezh maє іm'ya, scho i naming the class.
Constructors, like functions, can accept a set of parameters as input, like a stink of vicorist when the object is assembled.

Public class User(
int age;//field
String firstName;//field
String lastName;//field
public User(int age, String firstName, String lastName) (//constructor with three parameters
this.age = age;
this.firstName = firstName;
this.lastName = lastName;
}
}

It is obvious that constructors are called at the moment of object creation:

User user = new User(18, "Bendjamin", "Button");

In this way, we created an object for the User class, the Age field, which should have the value 18, the firstName is Bendjamin, and the lastName is a Button.
The choice of this constructor is richer, the lower yakbi mi were scribbled by hand:

User user=new User();
user.age = 18;
user.firstName = "Bendjamin";
user.lastName = "Button";

Krim tsgogo, if you victorious as designers, then the designer does not work for locks. In this way, since we only have a constructor with three parameters, we cannot create an object of this class without calling it:

User user = new User();//pardon, constructor for locking the day

Let's move on to some goodies intellij idea. Press alt+insert:

Tse menu of automatic creation of some brown speeches for the class. We are here at once to click on the item Constructor. Now that you have a class with fields, you can choose which fields you need to create a constructor and a programming environment for you to write some code. If you need one more constructor, then press the button again and add one more:

Public class User(
int age;//field
String firstName;//field
String lastName;//field
Public User(int age, String firstName, String lastName) (
this.age = age;
this.firstName = firstName;
this.lastName = lastName;
}

Public User(int age) (
this.age = age;
}
}

Now we can see the marvelous row this. The name of Zminnoi = the name of Zminnoi. The keyword which indicates what the stream instance of the class needs to set the value passed to the constructor. In this way, if we wrote a pose as a class, then user.age = age, where age is obviously changed.
You can click on other constructors, for example:

Public class User(
int age;//field
String firstName;//field
String lastName;//field

Public User(int age, String firstName, String lastName) (
this.age = age;
this.firstName = firstName;
this.lastName = lastName;
}

Public User(int age) (
this(age,"unknown", "unknown");//calling the constructor with three parameters
}
}

In addition, as your victorious class was in decline, then in order to call the father's constructor, it is necessary to block the keyword super
Constructors are needed for the cob nalashtuvannya of the object, as it is necessary to work like a dії z fields, for example, to proіnіtsіalіzuvati їх.

© 2022 androidas.ru - All about Android