What is initialization in java

Инициализация объектов, метод Initialize

— Хочу рассказать тебе об инициализации объектов. Когда объект создаётся – его переменным нужно присвоить стартовые данные. Чтобы не было ситуаций, когда ты обращаешься к объекту, а внутри у него нет нужной ему информации для правильной работы.

— Рассмотрим для примера объект типа File (файл). Минимальной необходимой информацией для файла является его имя. Создать файл без имени – это бессмыслица.

— Допустим, мы пишем свой класс для работы с файлами — MyFile, какая информация нужна каждому объекту этого класса?

— Имя файла, с которым этот объект будет работать?

— Правильно. Для этого добавим в наш класс метод initialize(). Это будет выглядеть примерно так:

class MyFile < private String filename = null; public void initialize(String name) < this.filename = name; > … >

— Мы добавили метод initialize, чтобы с объектом можно было работать – вызывать его методы. Это можно делать сразу после вызова метода initialize. Если с объектом работать нельзя, его называют невалидным (invalid), если можно – валидным (valid). Основная задача метода initialize – передать в объект все необходимые данные, чтобы сделать его валидным.

— Теперь усложним задачу. Вернее упростим. Как посмотреть. Представим, что другому программисту, который будет использовать наш класс, удобнее передавать в него не полное имя файла, а директорию и короткое имя файла. Мы бы смогли реализовать эту функциональность с помощью ещё одного метода initialize ( Java позволяет создавать несколько методов с одинаковыми именами ). Тогда наш класс стал бы выглядеть так:

class MyFile < private String filename = null; public void initialize(String name) < this.filename = name; > public void initialize(String folder, String name) < this.filename = folder + name; > … >

— А ещё, часто нужно создать временную копию файла рядом с текущим.

Читайте также:  Заполнение arraylist с клавиатуры java

— Мы можем сделать метод для этого случая?

class MyFile < private String filename = null; public void initialize(String name) < this.filename = name; > public void initialize(String folder, String name) < this.filename = folder + name; > // Файл filename будет находиться в той же директории, что и file. public void initialize(MyFile file, String name) < this.filename = file.getFolder() + name; > … >

— И что, я могу сделать таких методов сколько угодно?

— Разумные пределы, конечно, есть. Но, в принципе, да, сколько угодно.

— А когда надо вызывать метод initialize?

— Сразу после создания объекта, чтобы перевести его в валидное состояние:

MyFile file = new MyFile(); file.initialize("c:\data\a.txt"); String text = file.readText();
MyFile file = new MyFile(); file.initialize("c:\data∖", "a.txt"); String text = file.readText();
MyFile file = new MyFile(); file.initialize("c:\data\a.txt"); MyFile file2 = new MyFile(); file2.initialize(file, "a.txt"); String text = file2.readText();

— А что ещё за метод getFolder()?

— По логике этот метод должен возвращать строку с именем папки, в которой находится наш файл. Но мы его тут не писали, он чисто для фона.

Источник

Initializing Fields

As you have seen, you can often provide an initial value for a field in its declaration:

public class BedAndBreakfast < // initialize to 10 public static int capacity = 10; // initialize to false private boolean full = false; >

This works well when the initialization value is available and the initialization can be put on one line. However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

Note: It is not necessary to declare fields at the beginning of the class definition, although this is the most common practice. It is only necessary that they be declared and initialized before they are used.

Static Initialization Blocks

A static initialization block is a normal block of code enclosed in braces, < >, and preceded by the static keyword. Here is an example:

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

There is an alternative to static blocks — you can write a private static method:

The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.

Initializing Instance Members

Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.

Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

A final method cannot be overridden in a subclass. This is discussed in the lesson on interfaces and inheritance. Here is an example of using a final method for initializing an instance variable:

This is especially useful if subclasses might want to reuse the initialization method. The method is final because calling non-final methods during instance initialization can cause problems.

Previous page: Understanding Class Members
Next page: Summary of Creating and Using Classes and Objects

Источник

Creating Objects

As you know, a class provides the blueprint for objects; you create an object from a class. Each of the following statements taken from the CreateObjectDemo program creates an object and assigns it to a variable:

Point originOne = new Point(23, 94); Rectangle rectOne = new Rectangle(originOne, 100, 200); Rectangle rectTwo = new Rectangle(50, 100);

The first line creates an object of the Point class, and the second and third lines each create an object of the Rectangle class.

Each of these statements has three parts (discussed in detail below):

  1. Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
  2. Instantiation: The new keyword is a Java operator that creates the object.
  3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

Declaring a Variable to Refer to an Object

Previously, you learned that to declare a variable, you write:

This notifies the compiler that you will use name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable.

You can also declare a reference variable on its own line. For example:

If you declare originOne like this, its value will be undetermined until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object. For that, you need to use the new operator, as described in the next section. You must assign an object to originOne before you use it in your code. Otherwise, you will get a compiler error.

A variable in this state, which currently references no object, can be illustrated as follows (the variable name, originOne , plus a reference pointing to nothing):

Instantiating a Class

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

Note: The phrase «instantiating a class» means the same thing as «creating an object.» When you create an object, you are creating an «instance» of a class, therefore «instantiating» a class.

The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.

The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like:

Point originOne = new Point(23, 94); 

The reference returned by the new operator does not have to be assigned to a variable. It can also be used directly in an expression. For example:

int height = new Rectangle().height;

This statement will be discussed in the next section.

Initializing an Object

Here’s the code for the Point class:

This class contains a single constructor. You can recognize a constructor because its declaration uses the same name as the class and it has no return type. The constructor in the Point class takes two integer arguments, as declared by the code (int a, int b). The following statement provides 23 and 94 as values for those arguments:

Point originOne = new Point(23, 94);

The result of executing this statement can be illustrated in the next figure:

Here’s the code for the Rectangle class, which contains four constructors:

public class Rectangle < public int width = 0; public int height = 0; public Point origin; // four constructors public Rectangle() < origin = new Point(0, 0); >public Rectangle(Point p) < origin = p; >public Rectangle(int w, int h) < origin = new Point(0, 0); width = w; height = h; >public Rectangle(Point p, int w, int h) < origin = p; width = w; height = h; >// a method for moving the rectangle public void move(int x, int y) < origin.x = x; origin.y = y; >// a method for computing the area of the rectangle public int getArea() < return width * height; >>

Each constructor lets you provide initial values for the rectangle’s origin, width, and height, using both primitive and reference types. If a class has multiple constructors, they must have different signatures. The Java compiler differentiates the constructors based on the number and the type of the arguments. When the Java compiler encounters the following code, it knows to call the constructor in the Rectangle class that requires a Point argument followed by two integer arguments:

Rectangle rectOne = new Rectangle(originOne, 100, 200);

This calls one of Rectangle ‘s constructors that initializes origin to originOne . Also, the constructor sets width to 100 and height to 200. Now there are two references to the same Point object—an object can have multiple references to it, as shown in the next figure:

The following line of code calls the Rectangle constructor that requires two integer arguments, which provide the initial values for width and height. If you inspect the code within the constructor, you will see that it creates a new Point object whose x and y values are initialized to 0:

Rectangle rectTwo = new Rectangle(50, 100);

The Rectangle constructor used in the following statement doesn’t take any arguments, so it’s called a no-argument constructor:

Rectangle rect = new Rectangle();

All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent’s no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor ( Object does have one), the compiler will reject the program.

Источник

Оцените статью