-
Notifications
You must be signed in to change notification settings - Fork 0
add all classes #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| package ru.otus.vadim.ivanov.java.basic.lesson11.oop2; | ||
|
|
||
| //обычные животные | ||
| public abstract class Animal { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Всех животных стоило бы вынести в отдельный пакет
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. В задании это явно нигде не прописано. Ошибку понял, учту на будущее. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ну задание не должно описывать те вещи, о которых должен заботиться сам программист
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Для человека который ничего не разрабатывал на яве, это не совсем очевидно. К тому же, вы при демонстрации примеров часто делаете каждый класс в отдельном файле в том же пакете There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Согласен, на занятии могу это не часто показывать, и поэтому проговариваю это на ревью кода. Ревью домашек это дополнительный материал для изучения в том числе |
||
| //имя | ||
| String name; | ||
|
|
||
| //скорость бега м/с | ||
| private int runSpeed; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Почему это поле закрыто от наследников?
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Принцип инкапсуляции говорит о том, что все что не используется явно, должно быть закрыто. Да и вы сами об этом говорили, открыть то, что необходимо. В предлагаемой мной реализации необходимости его открывать нет. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Не совсем так, давайте в общем чате обсудим
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ок |
||
|
|
||
| //выносливость ед. | ||
| int endurance; | ||
|
|
||
| //Все животные на 1 метр бега тратят 1 ед выносливости | ||
| private final int runCost = 1; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. private final int DEFAULT_RUN_COST = 1;
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ошибка, согласен. |
||
|
|
||
| public Animal(String name, int runSpeed, int endurance) { | ||
| this.name = name; | ||
| this.runSpeed = runSpeed; | ||
| this.endurance = endurance; | ||
| } | ||
|
|
||
| public int run(int distance) { | ||
| int actionCost = runCost * distance; | ||
| if(actionCost > endurance) { | ||
| System.out.println("Животное "+name+" устало"); | ||
| return -1; | ||
| } | ||
|
|
||
| endurance -= actionCost; | ||
| int time = distance/runSpeed; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Время лучше бы флоатом считать
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. В задании опять же не сказано, что нужна точность до мс. Почему нельзя использовать точность до секунды? Int для этого вполне достаточно. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Эх.. и правда про флоат не написал, ответ принимается) |
||
| System.out.println("Животное "+name+" пробежало "+distance+" м за "+time+" c"); | ||
|
|
||
| return time; | ||
| } | ||
|
|
||
| public void info() { | ||
| System.out.println("У "+name+" "+endurance+" ед выносливости."); | ||
| } | ||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| package ru.otus.vadim.ivanov.java.basic.lesson11.oop2; | ||
|
|
||
| public class Cat extends Animal { | ||
| public Cat(String name, int runSpeed, int endurance) { | ||
| super(name, runSpeed, endurance); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| package ru.otus.vadim.ivanov.java.basic.lesson11.oop2; | ||
|
|
||
| public class Dog extends WaterfowlAnimal { | ||
|
|
||
| public Dog(String name, int runSpeed, int swimSpeed, int endurance) { | ||
| super(name,runSpeed,swimSpeed,endurance); | ||
| } | ||
|
|
||
| @Override | ||
| int initSwimCost() { | ||
| // Собаки на 1 метр плавания - 2 ед. | ||
| return 2; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| package ru.otus.vadim.ivanov.java.basic.lesson11.oop2; | ||
|
|
||
| public class Horse extends WaterfowlAnimal { | ||
| public Horse(String name, int runSpeed, int swimSpeed, int endurance) { | ||
| super(name,runSpeed,swimSpeed,endurance); | ||
| } | ||
|
|
||
| @Override | ||
| int initSwimCost() { | ||
| //Лошади на 1 метр плавания тратят 4 единицы | ||
| return 4; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| package ru.otus.vadim.ivanov.java.basic.lesson11.oop2; | ||
|
|
||
| public class MainApp11 { | ||
|
|
||
| public static void main(String[] args) { | ||
| System.out.println("----hw11.oop2----"); | ||
|
|
||
| System.out.println("----Cat----"); | ||
| Cat barsik = new Cat("Barsik",10, 100); | ||
| barsik.info(); | ||
|
|
||
| barsik.run(10); | ||
| barsik.info(); | ||
|
|
||
| barsik.run(100); | ||
| barsik.info(); | ||
|
|
||
| System.out.println("----Dog----"); | ||
| Dog bobik = new Dog("Bobik",20,10,200); | ||
| bobik.info(); | ||
|
|
||
| bobik.run(100); | ||
| bobik.info(); | ||
|
|
||
| bobik.swim(10); | ||
| bobik.info(); | ||
|
|
||
| bobik.swim(150); | ||
|
|
||
| System.out.println("----Horse----"); | ||
| Horse maxim = new Horse("Maxim",100,50, 5000); | ||
| maxim.run(1000); | ||
| maxim.info(); | ||
| maxim.swim(500); | ||
| maxim.info(); | ||
|
|
||
|
|
||
|
|
||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| package ru.otus.vadim.ivanov.java.basic.lesson11.oop2; | ||
|
|
||
| //водоплавающие | ||
| public abstract class WaterfowlAnimal extends Animal { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. При такой структуре классов будет крайне сложно "смешивать" способности животных. Например, если добавилась бы логика травоядные(т)/хищные(х), то строилось бы большое дерево, плав/т, п/х, неплав/т, нп/х. А если добавим сюда третье свойство, то при добавлении придется переписывать все классы, чтобы переразнести их в разные группы Всю реализацию можно было оставить в Животном, только при попытке попросить поплавать кота, он бы просто отказывался от этого.
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Согласен, сложно. Возможно я не правильно понял задание "Кот плавать не умеет." - я понимаю как, у кота в принципе не должно быть метода swim, а как это реализовать без разделения на группы? Идея, про то, что у кота есть метод swim, но он при этом ничего не делает не совсем очевидна. А что метод swim будет возвращать? По условию он должен возвращать время или -1 в случае усталости. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. -1 скорее по логике означает невозможность выполнить действие, поэтому у кота свим может быть (типа попросим его поплавать), но он скажет нет и просто вернет -1
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Это ни разу не очевидно "Если выносливости не хватает, то возвращаем время -1" |
||
|
|
||
| private int swimCost; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Почему эти поля приватные?
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Они не используются нигде кроме текущего класса, зачем их делать открытыми ? |
||
| private int swimSpeed; | ||
| public WaterfowlAnimal(String name, int runSpeed, int swimSpeed, int endurance) { | ||
| super(name,runSpeed,endurance); | ||
| this.swimSpeed = swimSpeed; | ||
|
|
||
| this.swimCost = initSwimCost(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Это поле можно спокойно заполнять в конструкторе конкретного животного
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Правильную инициализацию этого поля мы оставляем на совесть разработчика, который будет писать конструктор конкретного животного, что опять же по моему мнению (не факт что истинному) не правильная стратегия. Необходимость реализовать initSwimCost - гарантирует наличие этого поля и его правильную инициализацию. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А что мешает совести разработчика криво заполнить поле в initSwimCost? Если оно прошито в родительском конструкторе, то сам родительский конструктор не даст его пропустить
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ну как бы они его не заполняли, метод должен вернуть int и наше поле тоже типа int, а значит работа алгоритма не нарушится, мы всегда получим int. Ошибка может быть только в самом значении, но от этого уже застраховать не возможно, ну или накручивать логику валидации |
||
|
|
||
| } | ||
|
|
||
| public int swim(int distance) { | ||
| int actionCost = swimCost * distance; | ||
| if(actionCost > endurance) { | ||
| System.out.println("Животное "+name+" устало"); | ||
| return -1; | ||
| } | ||
|
|
||
| endurance -= actionCost; | ||
| int time = distance/swimSpeed; | ||
| System.out.println("Животное "+name+" проплыло "+distance+" м за "+time+" c"); | ||
|
|
||
| return time; | ||
| } | ||
|
|
||
| abstract int initSwimCost(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Этот метод лишний
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Этот метод нужен для инициализации значения SwimCost у всех водоплавающих. Так как он абстрактный, то любое водоплавающее животное его реализует и это гарантирует, что всегда будет поле с названием SwimCost и оно всегда будет проинициализировано своим значением для конкретного животного.
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Опять же, идея не моя https://stackoverflow.com/questions/2613596/how-to-create-an-abstract-field There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Там у человека хитрый случай, в данном решении такой подход не требуется
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Спорить не буду, вы профи, вам виднее |
||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
По заданию требовался еще флаг усталости, чтобы в методе инфо потом сказать что животное устало по результату гонки
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В задаче нет ничего про флаг усталости, цитирую "Если выносливости не хватает, то возвращаем время -1 и указываем что у животного появилось состояние усталости. "
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Добавляем метод info(), который выводит в консоль состояние животного.
Как Вы отпечатаете состояние усталости если не отслеживаете его?)
Но согласен, можно сослаться на нечуткую формулировку дз и не делать это)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Состояние это текущее значение выносливости, просто вывожу его в консоль.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ок, согласен, вопрос снят)