|
|
|
private static метод
|
|||
|---|---|---|---|
|
#18+
Здравствуйте. Был вопрос в тесте: Which one of the following situations requires a method to be declared "private static"? Choice 1 The method is available only to the class, not to instances of the class. Choice 2 The method is called by other class methods but needs to be hidden from all other classes. Choice 3 The results of the method can be computed at compile-time and removed by the optimizer. Choice 4 The method is available only to classes that extend this class. Choice 5 The method is called only once at the time of class initialization. Терзают сомнения между 2 и 3 ответом, т.к. если объявить метод private statit, это будет означать также и final -> компилятор может это сделать, но 2-й кажется более очевидным и прикладным% ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 12.04.2006, 12:23 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
K1RUHAЗдравствуйте. Терзают сомнения между 2 и 3 ответом, т.к. если объявить метод private statit, это будет означать также и final -> компилятор может это сделать, но 2-й кажется более очевидным и прикладным% IMHO 5-й ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 12.04.2006, 12:53 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
Евгений Путилин IMHO 5-й Нет 5-й точно не подойдет. Это определение статического блока. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 12.04.2006, 12:58 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
Я за второй. А есть правильный ответ? ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 12.04.2006, 13:01 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
GMaxЯ за второй. А есть правильный ответ? Неа, ответов нет :) Поэтому и решил посовещаться. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 12.04.2006, 14:07 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
Похоже на второе. приват требуецца для того чтобы другие классы, включая наследников, не могли вызвать метод, а статик требуецца для того, чтобы иметь возможность вызвать из другого статик метода этого же класса. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 12.04.2006, 16:24 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
K1RUHAТерзают сомнения между 2 и 3 ответом, т.к. если объявить метод private statit, это будет означать также и final -> компилятор может это сделать, но 2-й кажется более очевидным и прикладным% Похоже, автор не знает еще, и что такое final. Правильный ответ - 2. А человека, который бы рассматривал вариант 3 как вероятный, я бы на работу не взял. За такой ответ нужно отнимать балы. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 12.04.2006, 16:43 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
Ненавижу регистрацию Похоже, автор не знает еще, и что такое final. Красным выделено почему private можно рассматривать как final. А чуть выше выделено, что код final-метода может быть вставлен в байт-код. Хотя мне казалось, что как раз компилятор может и вставить значение вычисленной функции, поэтому оба ответа казались правильными. Bruce Eckel Final methods There are two reasons for final methods. The first is to put a “lock” on the method to prevent any inheriting class from changing its meaning. This is done for design reasons when you want to make sure that a method’s behavior is retained during inheritance and cannot be overridden. [ Add Comment ] The second reason for final methods is efficiency. If you make a method final, you are allowing the compiler to turn any calls to that method into inline calls. When the compiler sees a final method call it can (at its discretion) skip the normal approach of inserting code to perform the method call mechanism (push arguments on the stack, hop over to the method code and execute it, hop back and clean off the stack arguments, and deal with the return value) and instead replace the method call with a copy of the actual code in the method body. This eliminates the overhead of the method call. Of course, if a method is big, then your code begins to bloat and you probably won’t see any performance gains from inlining, since any improvements will be dwarfed by the amount of time spent inside the method. It is implied that the Java compiler is able to detect these situations and choose wisely whether to inline a final method. However, it’s better to not trust that the compiler is able to do this and make a method final only if it’s quite small or if you want to explicitly prevent overriding. [ Add Comment ] final and private Any private methods in a class are implicitly final. Because you can’t access a private method, you can’t override it (even though the compiler doesn’t give an error message if you try to override it, you haven’t overridden the method, you’ve just created a new method). You can add the final specifier to a private method but it doesn’t give that method any extra meaning. [ Add Comment ] This issue can cause confusion, because if you try to override a private method (which is implicitly final) it seems to work: “Overriding” can only occur if something is part of the base-class interface. That is, you must be able to upcast an object to its base type and call the same method (the point of this will become clear in the next chapter). If a method is private, it isn’t part of the base-class interface. It is just some code that’s hidden away inside the class, and it just happens to have that name, but if you create a public, protected or “friendly” method in the derived class, there’s no connection to the method that might happen to have that name in the base class. Since a private method is unreachable and effectively invisible, it doesn’t factor into anything except for the code organization of the class for which it was defined. Ненавижу регистрацию А человека, который бы рассматривал вариант 3 как вероятный, я бы на работу не взял. За такой ответ нужно отнимать балы. Не надо быть столь категоричным, все могут ошибаться :) ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 12.04.2006, 17:45 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
K1RUHAХотя мне казалось, что как раз компилятор может и вставить значение вычисленной функции Для этого как минимум функция должна быть детерминированной и без побочных эффектов, чего в задании совершенно не указано. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 12.04.2006, 18:40 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
K1RUHA Ненавижу регистрацию Похоже, автор не знает еще, и что такое final. Красным выделено почему private можно рассматривать как final. А чуть выше выделено, что код final-метода может быть вставлен в байт-код. Хотя мне казалось, что как раз компилятор может и вставить значение вычисленной функции, поэтому оба ответа казались правильными. Bruce Eckel Final methods There are two reasons for final methods. The first is to put a “lock” on the method to prevent any inheriting class from changing its meaning. This is done for design reasons when you want to make sure that a method’s behavior is retained during inheritance and cannot be overridden. [ Add Comment ] The second reason for final methods is efficiency. If you make a method final, you are allowing the compiler to turn any calls to that method into inline calls. When the compiler sees a final method call it can (at its discretion) skip the normal approach of inserting code to perform the method call mechanism (push arguments on the stack, hop over to the method code and execute it, hop back and clean off the stack arguments, and deal with the return value) and instead replace the method call with a copy of the actual code in the method body. This eliminates the overhead of the method call. Of course, if a method is big, then your code begins to bloat and you probably won’t see any performance gains from inlining, since any improvements will be dwarfed by the amount of time spent inside the method. It is implied that the Java compiler is able to detect these situations and choose wisely whether to inline a final method. However, it’s better to not trust that the compiler is able to do this and make a method final only if it’s quite small or if you want to explicitly prevent overriding. [ Add Comment ] final and private Any private methods in a class are implicitly final. Because you can’t access a private method, you can’t override it (even though the compiler doesn’t give an error message if you try to override it, you haven’t overridden the method, you’ve just created a new method). You can add the final specifier to a private method but it doesn’t give that method any extra meaning. [ Add Comment ] This issue can cause confusion, because if you try to override a private method (which is implicitly final) it seems to work: “Overriding” can only occur if something is part of the base-class interface. That is, you must be able to upcast an object to its base type and call the same method (the point of this will become clear in the next chapter). If a method is private, it isn’t part of the base-class interface. It is just some code that’s hidden away inside the class, and it just happens to have that name, but if you create a public, protected or “friendly” method in the derived class, there’s no connection to the method that might happen to have that name in the base class. Since a private method is unreachable and effectively invisible, it doesn’t factor into anything except for the code organization of the class for which it was defined. Ненавижу регистрацию А человека, который бы рассматривал вариант 3 как вероятный, я бы на работу не взял. За такой ответ нужно отнимать балы. Не надо быть столь категоричным, все могут ошибаться :) С красным никто не спорит. Только ваша ошибка в том, что вы думаете, будто бы Choice 3 соответствует final-методу. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 13.04.2006, 00:09 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
K1RUHAБыл вопрос в тесте: Which one of the following situations requires a method to be declared "private static"? Подходит только ответ 3 (да и то ...) потому как Choice 1 The method is available only to the class, not to instances of the class. бред собачий Choice 2 The method is called by other class methods but needs to be hidden from all other classes. не обязан быть static поскольку не оговорено что "other class methods" могут быть static. Choice 3 The results of the method can be computed at compile-time and removed by the optimizer. Вот только в таком варианте при параметрах константах компилятор может вычислить значение и remove by the optimizer а не вставлять "inline" bytecode. Choice 4 The method is available only to classes that extend this class. бред Choice 5 The method is called only once at the time of class initialization. не обязан быть private Сергей ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 13.04.2006, 01:19 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
ska Подходит только ответ 3 (да и то ...) потому как А на самом деле и 3 не обязательно требует static - лишь бы к instance обращения не было, т.е. static по сути а не по описанию, так что просто вопрос некорректный. Составителей НА МЫЛО ! ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 13.04.2006, 01:24 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
skaА на самом деле и 3 не обязательно требует static... Хотите посмеяться - жаба 1.4 и 1.5 вообще не оптимизирует :-)) Проверил IBM (rs6000 & as/400), HP (pa-risc), SUN. А вот IBM JDK 1.1.8 для Win действительно соптимизировал и независимо от static но "на всякий случай" функцию оставил. тест: Код: plaintext 1. 2. 3. 4. 5. 6. 7. 8. 9. вот что показал jad: Код: plaintext 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 13.04.2006, 04:32 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
K1RUHA Евгений Путилин IMHO 5-й Нет 5-й точно не подойдет. Это определение статического блока. Ребята вы что прикалываетесь? Читатйе вопрос, 3 и 4 отпадают т.к. добавленны для кучки не имеют к вопросу никакого отношения. Для 1 не нужно private для 2 не нужен static. У меня вот вопрос если нужно проинициализировать static final перепенную как вы будите поступать? ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 13.04.2006, 10:17 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
Евгений Путилин K1RUHA Евгений Путилин IMHO 5-й Нет 5-й точно не подойдет. Это определение статического блока. Ребята вы что прикалываетесь? Читатйе вопрос, 3 и 4 отпадают т.к. добавленны для кучки не имеют к вопросу никакого отношения. Для 1 не нужно private для 2 не нужен static. У меня вот вопрос если нужно проинициализировать static final перепенную как вы будите поступать? Только при объявлении ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 13.04.2006, 10:28 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
ska Choice 2 The method is called by other class methods but needs to be hidden from all other classes.не обязан быть static поскольку не оговорено что "other class methods" могут быть static. А почему это должно быть оговорено? создать статик метод также просто как и не статик, и это будет метод класса. Противоречий не вижу. К тому же, если учитывать что в пункте первом делаецца различие между методами класса и методами инстансов класса, то логично что когда во втором пункте говорицца о метода класса - подразумеваюцца что это могут быть как статик так и не статик методы (либо вообще только статик - но это уже спорно :)) ну это конечно имхо. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 13.04.2006, 14:42 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
KPIISТолько при объявлении а так Код: plaintext 1. 2. 3. 4. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 13.04.2006, 15:07 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
expp KPIISТолько при объявленииа так Код: plaintext 1. 2. 3. 4. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 13.04.2006, 16:16 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
Jozic expp KPIISТолько при объявленииа так Код: plaintext 1. 2. 3. 4. Это подтверждает что статик блок может быть использован при инициализации статик переменных. И приват статик метод нот реквайред в этой ситуации :) ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 13.04.2006, 16:21 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
Jozic она у вас не final а так? Код: plaintext 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. ----------------------------------- The Bat + My Gate Posted via ActualForum NNTP Server 1.3 ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 13.04.2006, 16:25 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
Deady[quot Jozic] она у вас не final а так? Код: plaintext 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. а я кстати не люблю таких конструкций как static{ sv = 9000; } мне не нравится читать такой код ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 13.04.2006, 16:29 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
извиняюсь, тупанул static final иниц-ся строго при объявлении. это я неудачно на обычные final ы посмотрел где так можно. а конструкция static{} вполне юзабильна ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 14.04.2006, 03:05 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
единственный случай где можно применять это 2й, а вот чтобы требовалось.. некватает шестого варианта "ни один из перечисленных" ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 14.04.2006, 15:23 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
2 KPIIS: автора я кстати не люблю таких конструкций как static{ sv = 9000; } мне не нравится читать такой код напрасно, instance initialisation blocks ,к примеру, очень удобный подход если нужно дублировать код в нескольких конструкторах. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 14.04.2006, 15:34 |
|
||
|
private static метод
|
|||
|---|---|---|---|
|
#18+
s-e-r-g-eединственный случай где можно применять это 2й, а вот чтобы требовалось.. некватает шестого варианта "ни один из перечисленных" Choice 2 The method is called by other class methods but needs to be hidden from all other classes. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 15.04.2006, 00:00 |
|
||
|
|

start [/forum/topic.php?fid=59&msg=33661261&tid=2149507]: |
0ms |
get settings: |
8ms |
get forum list: |
16ms |
check forum access: |
3ms |
check topic access: |
3ms |
track hit: |
155ms |
get topic data: |
9ms |
get forum data: |
2ms |
get page messages: |
58ms |
get tp. blocked users: |
1ms |
| others: | 203ms |
| total: | 458ms |

| 0 / 0 |
