Главная » Uncategorized » Структуры Java

Структуры Java

Structs are occasionally useful

Some programming languages (such as C and Algol 68) formally define the idea of a struct, as a simple way of grouping together related data. Although the Java Language Specification doesn’t formally define structs, the equivalent of a struct can certainly be created in Java. Here’s an example of a struct which gathers together data related to books:

import java.math.BigDecimal;

/** Simple struct containing book information. */
final class Book {
  String TITLE;
  String ISBN;
  Integer NUM_PAGES;
  BigDecimal PRICE;

Many dislike using such structures since they’re open to abuse. Any public, mutable members are dangerous, since there’s no encapsulation. This is indeed a valid objection to their wide-spread use. However, structs can still be occasionally useful, and one shouldn’t be afraid to use them when appropriate. In particular, if the data is neither public nor mutable, then the usual objections to structs lose much of their force.

For example, if the above Book class was in fact a nested private class, and was just a dumb little data carrier used only inside a single class, then there would be little objection to using it:

    like all private data, the struct would be invisible outside the class
    since the struct’s members are all immutable, then there’s no way to change the state of its member objects

Добавить комментарий

Заполните поля или щелкните по значку, чтобы оставить свой комментарий:

Логотип WordPress.com

Для комментария используется ваша учётная запись WordPress.com. Выход / Изменить )

Фотография Twitter

Для комментария используется ваша учётная запись Twitter. Выход / Изменить )

Фотография Facebook

Для комментария используется ваша учётная запись Facebook. Выход / Изменить )

Google+ photo

Для комментария используется ваша учётная запись Google+. Выход / Изменить )

Connecting to %s