Package com company что это java
Перейти к содержимому

Package com company что это java

  • автор:

(JAVA) Почему мне нужно указывать com.company в начале моей программы и как работает этот код?

В общем, я новичок в Java и прохожу курс. Во-первых, я не понимаю, зачем мне com.company в начале этой программы (с использованием IntelliJ IDEA и JDK 9.0.1). Во-вторых, я не понимаю, как эта программа вызывает метод «calculateTax», потому что единственный вызов метода — это когда инициализируется двойная переменная «total». Вот код:

Итого: 15,0
Налог: 1,2
Итого: 16,2

Процесс завершен с кодом выхода 0

1 ответ

Использование com.company не обязательно, вы можете использовать собственное имя пакета. Пакет используется для организации классов, принадлежащих к одной категории или схожей функциональности. Уроки можно загружать как группу, а не по одному.

Для вычисления итога вам понадобится результат метода calculateTax, поэтому вычисление итогов будет приостановлено и будет вызван метод calculateTax. Когда метод calculateTax завершен и результат будет возвращен, итоговый расчет будет возобновлен.

(JAVA) Why do I need to put com.company at the start of my program and how does this code work?

So basically, I am a beginner to Java, and I am taking a course. Firstly, I don’t understand why I need com.company at the beginning of this program (using IntelliJ IDEA and JDK 9.0.1). Secondly, I don’t understand how this program calls the «calculateTax» method because the only method call is when the double variable «total» is being initialized. Here’s the code:

Here’s the output:

Subtotal: 15.0
Tax: 1.2
Total: 16.2

Process finished with exit code 0

Thanks in advance 🙂

1 Answer 1

It is not mandatory to use com.company, you can use your own package name. Package is used to organize classes belonging to the same category or similar functionality. Classes can be downloaded faster as a group rather than one at a time.

To calculate total you will need the result of calculateTax method, so total calculation will be paused and calculateTax method will be called. When calculateTax method is finished and result is returned then total calculation will be resumed.

Java Naming Conventions

Java naming conventions are sort of guidelines that application programmers are expected to follow to produce consistent and readable code throughout the application. If teams do not follow these conventions, they may collectively write an application code that is hard to read and difficult to understand.

Java heavily uses Camel Case notations for naming the methods, variables etc. and TitleCase notations for classes and interfaces.

Let’s understand these naming conventions in detail with examples.

1. Naming Packages

Package names must be a group of words starting with all lowercase domain names (e.g. com, org, net, etc). Subsequent parts of the package name may be different according to an organization’s own internal naming conventions.

2. Naming Classes

In Java, class names generally should be nouns, in title-case with the first letter of each separate word capitalized. e.g.

3. Naming Interfaces

In Java, interfaces names, generally, should be adjectives. Interfaces should be in the title case with the first letter of each separate word capitalized. In some cases, interfaces can be nouns as well when they present a family of classes e.g. List and Map .

4. Naming Methods

Methods always should be verbs. They represent action and the method name should clearly state the action they perform. The method name can be single or 2-3 words as needed to clearly represent the action. Words should be in camel case notation.

5. Naming Variables

All instance, static and method parameter variable names should be in camel case notation. They should be short and enough to describe their purpose. Temporary variables can be a single character e.g. the counter in the loops.

6. Constant Naming Conventions

Java constants should be all UPPERCASE where words are separated by underscore character (“_”). Make sure to use the final modifier with constant variables.

7. Naming Generic Types

Generic type parameter names should be uppercase single letters. The letter ‘T’ for type is typically recommended. In JDK classes, E is used for collection elements, S is used for service loaders, and K and V are used for map keys and values.

8. Naming Enums

Similar to class constants, enumeration names should be all uppercase letters.

9. Naming Annotations

Annotation names follow title case notation. They can be adjectives, verbs, or nouns based on the requirements.

In this post, we discussed the naming conventions in Java to be followed for consistent writing of code which makes the code more readable and maintainable.

Naming conventions are probably the first best practice to follow while writing clean code in any programming language.

Package Design Checklist, Naming

Consistency. The long-established Java convention is to generate a unique root package name by reversing the internet domain name of the developing organization. When the organization owns multiple internet domain names, the official domain name is used.

Exceptions:

This rule applies to all new APIs and all major new API versions. It does not apply to published APIs, for which item 1.1.11 takes precedence.

If the package naming is changed (for example as part of product rebranding), a major new API version is released. The old package names are deprecated, but kept for backwards compatibility, satisfying item 1.1.11

1.2.2. Use a stable product or product family name at the second level of the package name

Rationale:

Simplicity and Consistency. Developers like short API package names and ideally you should place API packages directly under the root namespace. However, multiple independent business units or product groups may share the root namespace of larger organizations. It is customary to subdivide the root namespace and give each independent unit full control over their own namespace. When the namespace is organized like this, place the API package directly under the namespace you control.

When nobody is officially in charge of controlling the organization’s root namespace, insert a stable product or product family name between the root namespace and the API package. Don’t use the product’s external marketing name, over which you have no control. Use a generic dictionary term or a widely accepted industry concept which best describes your product.

Talk to your product manager about what product name to use.

Do this:

Don’t do this:

Exceptions:

If the API itself is the product, place the API package directly under the root namespace.

1.2.3. Use the name of the API as the final part of the package name

Rationale:

Consistency. Developers scan the end of import statements to see what is being imported and expect API names to appear there, so it is important that API classes are imported from a package clearly identified with the name of the API.

If the API is broken up into several packages as suggested in item 1.1.3, these packages should be named appropriately and placed inside a package bearing the name of the API.

For tips on choosing memorable API names see our naming guidelines.

Do this:

Do this:

Do this:

Don’t do this:

Don’t do this:

Don’t do this:

1.2.4. Consider marking implementation-only packages by including “internal” in the package name

Rationale:

<Simplicity, Consistency, Safety, and Evolution. We want to help developers quickly skip implementation packages when searching for APIs. We also want to warn them when trying to import from off-limits implementation packages. We recommend the word “internal” placed either at or just below the level of the API. Using “impl” serves the same purpose, but “internal” sounds better and should be used for consistency.

You can use the refactoring feature of a modern IDE to rename implementation packages in existing code. Import statements will be adjusted in all source files. Changing the name of implementation packages should have no impact on external clients.

Do this:

Do this:

Don’t do this:

Don’t do this:

1.2.5. Avoid composite names

Rationale:

Consistency. Composite package names are hard to read because the Java language specification only allows lowercase characters in package names. While underscores are allowed, they are very rarely used in practice, their usage being inconsistent both with the standard Java library names and with the mixed case naming conventions of the other Java identifiers. We ask you to avoid composite package names entirely. Use a single word whenever possible or a well-chosen abbreviation. Remember that we always use fully qualified package names and there is often enough information to give otherwise ambiguous terms a more precise meaning. Consider also that the fully qualified package name can easily become quite long.

Do this:

Do this:

Don’t do this:

Don’t do this:

1.2.6. Avoid using the same name for both package and class inside the package

Rationale:

Naming. It is generally not a good idea to give the same name to two different things. It becomes outright confusing when it is not clear what the API is. Is it the whole package or just the class?

Do this:

Do this:

Don’t do this:

1.2.7. Avoid using “api” in package names

Rationale:

Simplicity and Consistency. Callers import mostly APIs. The consistent use of the word “api” would make it redundant, as shown in the example below. This is why none of the core Java APIs has “api” in its package name. For consistency, we should follow the same convention.

Do this:

Don’t do this:

Don’t do this:

1.2.8. Do not use marketing, project, organizational unit or geographic location names

Rationale:

Naming. This is a simple application of the “do not use names which can change or may loose their meaning” rule. It deservers its place here only because such mistakes are very frequent in package names.

Don’t do this:

1.2.9. Do not use uppercase characters in package names

Rationale:

Consistency. This is a long-established Java convention.

alt=»Creative Commons Licence» width=»» />
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 Canada License.

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

Ваш адрес email не будет опубликован. Обязательные поля помечены *