Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Lecture 1.docx
Скачиваний:
1
Добавлен:
01.07.2025
Размер:
704 Кб
Скачать
☆

7.4 Defining methods of object creation (constructors)

Object creation is a special operation carried out by means of the class instance creation expression new. It consists in invocation of a constructor of the class.

A constructor is used to initialize fields of object. A constructor is a special kind of method, which:

  • has exactly the same name as the name of the class

  • has no return value

  • has a list of parameters (which might be empty)

Similarly to a definition of a method, a definition of a constructor may be preceded with an access modifier specifying whether the constructor may be invoked from other classes.

The syntax of the definition of a constructor: [public] class class_name {     // Definition of the constructor     [ access_modifier ] class_name(list_of_parameters) {         // constructor body     }          }

The class Pair may have the following constructors:

public class Pair {

private int a;

private int b;

public Pair(int x, int y) { // The fields a and b are

a = x; // initialized with the

b = y; // values of arguments

}

...

}

or:

public class Pair {

private int a, b;

public Pair(int x) { // The constructor has one parameter

a = x; // which initializes both fields

b = x;

}

...

}

A class may have many constructors with different lists of parameters. It is equivalent to method overloading. Using the above constructors we can easily create objects of the class Pair which are initialized with the given values: Pair p1 = new Pair(10,11);  // a pair 10, 11 Pair p2 = new Pair(2);         //a pair 2, 2

Constructors are always invoked by means of the class instance creation expression new.

A special constructor is the one which has no parameters. It is automatically added to a class definition when there are no other constructors defined. The body of the default constructor is empty. Thus, if we do not create any constructor in a class, then by class instance creation the generated default constructor will be invoked. Note: the default constructor is not generated if there is some other constructor defined in the class.

7.5. Example

Let us assume we need a program for managing a bookshop. The bookshop sells publications (books, journals, compact discs). Therefore, we are interested in publications in general. Each publication has: a title a publisher the year of publishing an identification number (ISBN, ISSN or other) a price a number of copies All these attributes are fields of the class.

public class Publication {

private String title;

private String publisher;

private int year;

private String ident;

private double price;

private int quantity;

...

}

Each publication is an object in our program. Objects must be initialized somehow. To ensure this we must supply a constructor which initializes fields of an object with the given parameters.

public class Publication {

private String title;

private String publisher;

private int year;

private String ident;

private double price;

private int quantity;

public Publication(String t, String pb, int y,

String i, double pr, int q)

{

title = t; // the field title is initialized with the value of that parameter t

publisher = pb; // the file publisher is initialized with the value of the parameter pb

year = y; // and so on ...

ident = i;

price = pr;

quantity = q;

}

...

}

Now we are able to create an object representing a book, for example entitled "Cats", published by "Dog & Sons", which costs 21.0 EUR.

Publication b = new Publication("Cats", "Dog & Sons", 2002, "ISBN6789", 21.0, 0);

What can we do with publications? We can buy them or sell them. We can ask for some information concerning the publication, like its title, publisher, year, identification or we may want to know how many copies there are in stock. It may happen that the price of a publication has changed, so we must have a way of modifying the object representing it. All these operations on publications are defined as methods.

public class Publication {

...

// methods:

public String getTitle() {

return title;

}

public String getPublisher() {

return publisher;

}

public int getYear() {

return year;

}

public String getIdent() {

return ident;

}

public double getPrice() {

return price;

}

public void setPrice(double p) {

price = p;

}

public int getQuantity() {

return quantity;

}

public void buy(int n) {

quantity += n;

}

public void sell(int n) {

quantity -= n;

}

}

We test the class Publication in another class named TestPub (in its method main).

class PubTest {

public static void main(String[] args) {

// instance creation

Publication b = new Publication("Cats", "Dog & Sons", 2002,

"ISBN6789", 21.0, 0);

int n = 10; // we buy 10 copies

b.buy(n);

double cost = n * b.getPrice(); // calculate the cost

System.out.println("To buy " + n + " copies:");

System.out.println(b.getTitle());

System.out.println(b.getPublisher());

System.out.println(b.getYear());

System.out.println(b.getIdent());

System.out.println("---------------\n: " + cost + " EUR was spent");

// sell 4 copies and check how many was left

b.sell(4);

System.out.println("---------------");

System.out.println("There are " + b.getQuantity() + " copies left");

}

}

To buy 10 copies: Cats Dog & Sons 2002 ISBN6789 --------------- 210.0 EUR was spent --------------- There are 6 copies left

Here is the output:

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]