From df1f5c6a4d9553cab11a5d24a415d6acb109dc5c Mon Sep 17 00:00:00 2001 From: Yaro4Java Date: Mon, 23 Dec 2019 22:32:16 +0300 Subject: [PATCH 01/10] filling entities ( Author, Book, SchoolBook ) and testing them --- .../com/epam/izh/rd/online/entity/Author.java | 67 +++++++++++++++++++ .../com/epam/izh/rd/online/entity/Book.java | 42 ++++++++++++ .../epam/izh/rd/online/entity/SchoolBook.java | 53 +++++++++++++++ 3 files changed, 162 insertions(+) diff --git a/src/main/java/com/epam/izh/rd/online/entity/Author.java b/src/main/java/com/epam/izh/rd/online/entity/Author.java index 166be587..89542f20 100644 --- a/src/main/java/com/epam/izh/rd/online/entity/Author.java +++ b/src/main/java/com/epam/izh/rd/online/entity/Author.java @@ -20,4 +20,71 @@ */ public class Author { + private String name; + private String lastName; + private LocalDate birthdate; + private String country; + + public Author() { + } + + public Author(String name, String lastName, LocalDate birthdate, String country) { + this.name = name; + this.lastName = lastName; + this.birthdate = birthdate; + this.country = country; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public LocalDate getBirthdate() { + return birthdate; + } + + public void setBirthdate(LocalDate birthdate) { + this.birthdate = birthdate; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public String toString() { + return "Author{" + + "name='" + name + '\'' + + ", lastName='" + lastName + '\'' + + ", birthdate=" + birthdate + + ", country='" + country + '\'' + + '}'; + } + } diff --git a/src/main/java/com/epam/izh/rd/online/entity/Book.java b/src/main/java/com/epam/izh/rd/online/entity/Book.java index 08bdccb8..605888a4 100644 --- a/src/main/java/com/epam/izh/rd/online/entity/Book.java +++ b/src/main/java/com/epam/izh/rd/online/entity/Book.java @@ -17,4 +17,46 @@ */ public abstract class Book { + private int numberOfPages; + private String name; + + public Book() { + } + + public Book(int numberOfPages, String name) { + this.numberOfPages = numberOfPages; + this.name = name; + } + + public int getNumberOfPages() { + return numberOfPages; + } + + public void setNumberOfPages(int numberOfPages) { + this.numberOfPages = numberOfPages; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public String toString() { + return super.toString(); + } + } diff --git a/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java b/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java index a9834db4..fade15c7 100644 --- a/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java +++ b/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java @@ -21,4 +21,57 @@ */ public class SchoolBook extends Book { + private String authorName; + private String authorLastName; + private LocalDate publishDate; + + public SchoolBook() { + } + + public SchoolBook(int numberOfPages, String name, String authorName, String authorLastName, LocalDate publishDate) { + super(numberOfPages, name); + this.authorName = authorName; + this.authorLastName = authorLastName; + this.publishDate = publishDate; + } + + public String getAuthorName() { + return authorName; + } + + public void setAuthorName(String authorName) { + this.authorName = authorName; + } + + public String getAuthorLastName() { + return authorLastName; + } + + public void setAuthorLastName(String authorLastName) { + this.authorLastName = authorLastName; + } + + public LocalDate getPublishDate() { + return publishDate; + } + + public void setPublishDate(LocalDate publishDate) { + this.publishDate = publishDate; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public String toString() { + return super.toString(); + } + } From aa0b4866dde58679dc6abf34020a4ce9b69eccd9 Mon Sep 17 00:00:00 2001 From: Yaro4Java Date: Mon, 23 Dec 2019 23:04:16 +0300 Subject: [PATCH 02/10] experimenting with classes within the main() method --- src/main/java/com/epam/izh/rd/online/Main.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/main/java/com/epam/izh/rd/online/Main.java b/src/main/java/com/epam/izh/rd/online/Main.java index e3939a4b..acd58bbf 100644 --- a/src/main/java/com/epam/izh/rd/online/Main.java +++ b/src/main/java/com/epam/izh/rd/online/Main.java @@ -1,9 +1,23 @@ package com.epam.izh.rd.online; +import com.epam.izh.rd.online.entity.Author; + public class Main { public static void main(String[] args) { + {/* SECTION FOR DEBUGGING CLASS Author */ + + Author author1 = new Author(); + + author1.setName("Yaroslav"); + author1.setCountry("Russia"); + + System.out.println(author1.toString()); + System.out.println("\nHash code is " + author1.hashCode()); + + }/* END OF DEBUGGING CLASS Author */ + } } From a60efef2edad131b55e0cec8a222fd25c55c307f Mon Sep 17 00:00:00 2001 From: Yaro4Java Date: Tue, 24 Dec 2019 21:43:04 +0300 Subject: [PATCH 03/10] generating another implementation of hashCode() and equals() methods --- .../com/epam/izh/rd/online/entity/Author.java | 20 ++++++++++++++---- .../com/epam/izh/rd/online/entity/Book.java | 16 ++++++++++---- .../epam/izh/rd/online/entity/SchoolBook.java | 21 +++++++++++++++---- 3 files changed, 45 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/epam/izh/rd/online/entity/Author.java b/src/main/java/com/epam/izh/rd/online/entity/Author.java index 89542f20..7c2096d3 100644 --- a/src/main/java/com/epam/izh/rd/online/entity/Author.java +++ b/src/main/java/com/epam/izh/rd/online/entity/Author.java @@ -68,13 +68,25 @@ public void setCountry(String country) { } @Override - public int hashCode() { - return super.hashCode(); + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Author author = (Author) o; + + if (name != null ? !name.equals(author.name) : author.name != null) return false; + if (lastName != null ? !lastName.equals(author.lastName) : author.lastName != null) return false; + if (birthdate != null ? !birthdate.equals(author.birthdate) : author.birthdate != null) return false; + return country != null ? country.equals(author.country) : author.country == null; } @Override - public boolean equals(Object obj) { - return super.equals(obj); + public int hashCode() { + int result = name != null ? name.hashCode() : 0; + result = 31 * result + (lastName != null ? lastName.hashCode() : 0); + result = 31 * result + (birthdate != null ? birthdate.hashCode() : 0); + result = 31 * result + (country != null ? country.hashCode() : 0); + return result; } @Override diff --git a/src/main/java/com/epam/izh/rd/online/entity/Book.java b/src/main/java/com/epam/izh/rd/online/entity/Book.java index 605888a4..8d029838 100644 --- a/src/main/java/com/epam/izh/rd/online/entity/Book.java +++ b/src/main/java/com/epam/izh/rd/online/entity/Book.java @@ -45,13 +45,21 @@ public void setName(String name) { } @Override - public int hashCode() { - return super.hashCode(); + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Book book = (Book) o; + + if (numberOfPages != book.numberOfPages) return false; + return name != null ? name.equals(book.name) : book.name == null; } @Override - public boolean equals(Object obj) { - return super.equals(obj); + public int hashCode() { + int result = numberOfPages; + result = 31 * result + (name != null ? name.hashCode() : 0); + return result; } @Override diff --git a/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java b/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java index fade15c7..1419df35 100644 --- a/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java +++ b/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java @@ -60,13 +60,26 @@ public void setPublishDate(LocalDate publishDate) { } @Override - public int hashCode() { - return super.hashCode(); + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + if (!super.equals(o)) return false; + + SchoolBook that = (SchoolBook) o; + + if (authorName != null ? !authorName.equals(that.authorName) : that.authorName != null) return false; + if (authorLastName != null ? !authorLastName.equals(that.authorLastName) : that.authorLastName != null) + return false; + return publishDate != null ? publishDate.equals(that.publishDate) : that.publishDate == null; } @Override - public boolean equals(Object obj) { - return super.equals(obj); + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (authorName != null ? authorName.hashCode() : 0); + result = 31 * result + (authorLastName != null ? authorLastName.hashCode() : 0); + result = 31 * result + (publishDate != null ? publishDate.hashCode() : 0); + return result; } @Override From e380d88bc93e4e416f0edd20bb671655ae3ca2ed Mon Sep 17 00:00:00 2001 From: Yaro4Java Date: Thu, 26 Dec 2019 00:21:47 +0300 Subject: [PATCH 04/10] playing with hashCode() and assertions in main() method --- .../java/com/epam/izh/rd/online/Main.java | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/epam/izh/rd/online/Main.java b/src/main/java/com/epam/izh/rd/online/Main.java index acd58bbf..059c6091 100644 --- a/src/main/java/com/epam/izh/rd/online/Main.java +++ b/src/main/java/com/epam/izh/rd/online/Main.java @@ -1,6 +1,8 @@ package com.epam.izh.rd.online; import com.epam.izh.rd.online.entity.Author; +import org.springframework.util.Assert; +import org.springframework.util.SocketUtils; public class Main { @@ -13,11 +15,44 @@ public static void main(String[] args) { author1.setName("Yaroslav"); author1.setCountry("Russia"); + class FreakAuthor extends Author { + public FreakAuthor(String name) { + this.setName(name); + } + + @Override + public int hashCode() { + return Object.class.hashCode(); + } + + } + + FreakAuthor freak = new FreakAuthor("John"); + System.out.println(author1.toString()); - System.out.println("\nHash code is " + author1.hashCode()); + System.out.println("\nHash code1 for author " + author1.getName() + " is " + author1.hashCode()); + System.out.println("Hash code2 for author " + author1.getName() + " is " + author1.hashCode()); + System.out.println("Hash code3 for author " + author1.getName() + " is " + author1.hashCode()); + + System.out.println("\nHash code1 for author " + freak.getName() + " is " + freak.hashCode()); + System.out.println("Hash code2 for author " + freak.getName() + " is " + freak.hashCode()); + System.out.println("Hash code3 for author " + freak.getName() + " is " + freak.hashCode()); }/* END OF DEBUGGING CLASS Author */ + + {/* SECTION FOR PLAYING WITH ASSERTIONS */ + + try { + Assert.isTrue(1 == 2, "What? 1 == 2? That's not true!!!"); + } /*catch ( IllegalArgumentException e ) { + System.out.println("What was that?!"); + }*/ catch ( Exception e ) { + System.out.println("\nIt was just an exception. Don't worry, be happy.\n"); + } + + }/* END OF DEBUGGING ASSERTIONS */ + } } From d8341d94a8a56d583a26d7a290b31893e5feb34e Mon Sep 17 00:00:00 2001 From: Yaro4Java Date: Fri, 27 Dec 2019 00:19:10 +0300 Subject: [PATCH 05/10] playing with assertions in main() method --- src/main/java/com/epam/izh/rd/online/Main.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/epam/izh/rd/online/Main.java b/src/main/java/com/epam/izh/rd/online/Main.java index 059c6091..eb818caa 100644 --- a/src/main/java/com/epam/izh/rd/online/Main.java +++ b/src/main/java/com/epam/izh/rd/online/Main.java @@ -44,7 +44,8 @@ public int hashCode() { {/* SECTION FOR PLAYING WITH ASSERTIONS */ try { - Assert.isTrue(1 == 2, "What? 1 == 2? That's not true!!!"); + Assert.isTrue(1 == 1, "What? 1 == 2? That's not true!!!"); + System.out.println("\nAssertion is successful. The requirement was met. Good job, man!\n"); } /*catch ( IllegalArgumentException e ) { System.out.println("What was that?!"); }*/ catch ( Exception e ) { From 2fbac844628e1505daf8ae3872df2024c09d5347 Mon Sep 17 00:00:00 2001 From: Yaro4Java Date: Sat, 28 Dec 2019 22:18:36 +0300 Subject: [PATCH 06/10] playing with constructors in main() method --- .../java/com/epam/izh/rd/online/Main.java | 132 ++++++++++++++---- .../com/epam/izh/rd/online/entity/Author.java | 15 +- 2 files changed, 118 insertions(+), 29 deletions(-) diff --git a/src/main/java/com/epam/izh/rd/online/Main.java b/src/main/java/com/epam/izh/rd/online/Main.java index eb818caa..85f52458 100644 --- a/src/main/java/com/epam/izh/rd/online/Main.java +++ b/src/main/java/com/epam/izh/rd/online/Main.java @@ -1,6 +1,7 @@ package com.epam.izh.rd.online; import com.epam.izh.rd.online.entity.Author; +import com.sun.xml.internal.ws.addressing.WsaActionUtil; import org.springframework.util.Assert; import org.springframework.util.SocketUtils; @@ -9,51 +10,128 @@ public class Main { public static void main(String[] args) { {/* SECTION FOR DEBUGGING CLASS Author */ +// +// Author author1 = new Author(); +// +// author1.setName("Yaroslav"); +// author1.setCountry("Russia"); +// +// class FreakAuthor extends Author { +// public FreakAuthor(String name) { +// this.setName(name); +// } +// +// @Override +// public int hashCode() { +// return Object.class.hashCode(); +// } +// +// } +// +// FreakAuthor freak = new FreakAuthor("John"); +// +// System.out.println("author1.objectToString(): " + author1.objectToString()); +// System.out.println("author1.toString(): " + author1.toString()); +// System.out.println("\n" + "author1 is the following " + author1.toString()); +// +// System.out.println("\nHash code1 for author " + author1.getName() + " is " + author1.hashCode()); +// System.out.println("Hash code2 for author " + author1.getName() + " is " + author1.hashCode()); +// System.out.println("Hash code3 for author " + author1.getName() + " is " + author1.hashCode()); +// +// System.out.println("\nHash code1 for author " + freak.getName() + " is " + freak.hashCode()); +// System.out.println("Hash code2 for author " + freak.getName() + " is " + freak.hashCode()); +// System.out.println("Hash code3 for author " + freak.getName() + " is " + freak.hashCode()); +// System.out.println("author1.ToStringHash(): " + author1.ToStringHash()); + + }/* END OF DEBUGGING CLASS Author */ + + + {/* SECTION FOR PLAYING WITH ASSERTIONS */ + + try { + Assert.isTrue(1 == 1, "What? 1 == 2? That's not true!!!"); + System.out.println("\nAssertion is successful. The requirement was met. Good job, man!"); + } /*catch ( IllegalArgumentException e ) { + System.out.println("What was that?!"); + }*/ catch ( Exception e ) { + System.out.println("\nIt was just an exception. Don't worry, be happy."); + } + + }/* END OF DEBUGGING ASSERTIONS */ - Author author1 = new Author(); - author1.setName("Yaroslav"); - author1.setCountry("Russia"); + {/* SECTION FOR PLAYING WITH CONSTRUCTORS */ - class FreakAuthor extends Author { - public FreakAuthor(String name) { - this.setName(name); + class A { + A() { + System.out.println("A() constructor is working ..."); + } + + A( String a ) { + System.out.println("A('" + a + "') constructor is working ..."); } @Override - public int hashCode() { - return Object.class.hashCode(); + public String toString() { + return "instance of class A = {}"; + } + } + + class B extends A { + String bField; + B() { + System.out.println("B() constructor is working ..."); } + @Override + public String toString() { + return "instance of class B = { " + + "bField='" + bField + '\'' + + " }"; + } } - FreakAuthor freak = new FreakAuthor("John"); + class C extends B { + C() { + System.out.println("C() constructor is working ..."); + } - System.out.println(author1.toString()); - System.out.println("\nHash code1 for author " + author1.getName() + " is " + author1.hashCode()); - System.out.println("Hash code2 for author " + author1.getName() + " is " + author1.hashCode()); - System.out.println("Hash code3 for author " + author1.getName() + " is " + author1.hashCode()); + C(String s) { + System.out.println("C('" + s + "') constructor is working ..."); + bField = s; + } - System.out.println("\nHash code1 for author " + freak.getName() + " is " + freak.hashCode()); - System.out.println("Hash code2 for author " + freak.getName() + " is " + freak.hashCode()); - System.out.println("Hash code3 for author " + freak.getName() + " is " + freak.hashCode()); + @Override + public String toString() { + return "instance of class C = { " + + "bField='" + bField + '\'' + + " }"; + } + } - }/* END OF DEBUGGING CLASS Author */ + System.out.println("\nCreating instance of class A with the A() constructor:"); + A aInstance1 = new A(); + System.out.println("aInstance1 was just born: " + aInstance1.toString()); + System.out.println("\nCreating instance of class A with the A(String) constructor:"); + A aInstance2 = new A("just a string"); + System.out.println("aInstance2 was just born: " + aInstance2.toString()); - {/* SECTION FOR PLAYING WITH ASSERTIONS */ + System.out.println("\nCreating instance of class B with the B() constructor:"); + B bInstance = new B(); + System.out.println("bInstance was just born: " + bInstance.toString()); - try { - Assert.isTrue(1 == 1, "What? 1 == 2? That's not true!!!"); - System.out.println("\nAssertion is successful. The requirement was met. Good job, man!\n"); - } /*catch ( IllegalArgumentException e ) { - System.out.println("What was that?!"); - }*/ catch ( Exception e ) { - System.out.println("\nIt was just an exception. Don't worry, be happy.\n"); - } + System.out.println("\nCreating instance of class C with the C() constructor:"); + C cInstance1 = new C(); + System.out.println("cInstance1 was just born: " + cInstance1.toString()); - }/* END OF DEBUGGING ASSERTIONS */ + System.out.println("\nCreating instance of class C with the C(String) constructor:"); + C cInstance2 = new C("some string"); + System.out.println("cInstance2 was just born: " + cInstance2.toString()); + + }/* END OF DEBUGGING CONSTRUCTORS */ + System.exit(0); } } diff --git a/src/main/java/com/epam/izh/rd/online/entity/Author.java b/src/main/java/com/epam/izh/rd/online/entity/Author.java index 7c2096d3..ce2772ee 100644 --- a/src/main/java/com/epam/izh/rd/online/entity/Author.java +++ b/src/main/java/com/epam/izh/rd/online/entity/Author.java @@ -91,12 +91,23 @@ public int hashCode() { @Override public String toString() { - return "Author{" + + return "instance of class Author: { " + "name='" + name + '\'' + ", lastName='" + lastName + '\'' + ", birthdate=" + birthdate + ", country='" + country + '\'' + - '}'; + " }"; + } + + // Original method toString() + public String objectToString() { + return super.toString(); + } + + + public String ToStringHash() { + return Object.class.hashCode() + " ( " + Integer.toHexString(Object.class.hashCode()) + " )"; + } } From 8461109b28ec80cb904e72f1f7345864039176f1 Mon Sep 17 00:00:00 2001 From: Yaro4Java Date: Mon, 30 Dec 2019 16:01:44 +0300 Subject: [PATCH 07/10] playing with early and late binding in main() method --- .../java/com/epam/izh/rd/online/Main.java | 180 +++++++++++++++++- 1 file changed, 177 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/epam/izh/rd/online/Main.java b/src/main/java/com/epam/izh/rd/online/Main.java index 85f52458..37af731e 100644 --- a/src/main/java/com/epam/izh/rd/online/Main.java +++ b/src/main/java/com/epam/izh/rd/online/Main.java @@ -1,10 +1,13 @@ package com.epam.izh.rd.online; import com.epam.izh.rd.online.entity.Author; +import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList; import com.sun.xml.internal.ws.addressing.WsaActionUtil; import org.springframework.util.Assert; import org.springframework.util.SocketUtils; +import java.util.ArrayList; + public class Main { public static void main(String[] args) { @@ -48,20 +51,26 @@ public static void main(String[] args) { {/* SECTION FOR PLAYING WITH ASSERTIONS */ + System.out.println("\n/* SECTION FOR PLAYING WITH ASSERTIONS */\n"); + try { Assert.isTrue(1 == 1, "What? 1 == 2? That's not true!!!"); - System.out.println("\nAssertion is successful. The requirement was met. Good job, man!"); + System.out.println("Assertion is successful. The requirement was met. Good job, man!"); } /*catch ( IllegalArgumentException e ) { System.out.println("What was that?!"); }*/ catch ( Exception e ) { - System.out.println("\nIt was just an exception. Don't worry, be happy."); + System.out.println("It was just an exception. Don't worry, be happy."); } + System.out.println("\n/* END OF PLAYING WITH ASSERTIONS */\n"); + }/* END OF DEBUGGING ASSERTIONS */ {/* SECTION FOR PLAYING WITH CONSTRUCTORS */ + System.out.println("\n/* SECTION FOR PLAYING WITH CONSTRUCTORS */\n"); + class A { A() { System.out.println("A() constructor is working ..."); @@ -109,7 +118,7 @@ public String toString() { } } - System.out.println("\nCreating instance of class A with the A() constructor:"); + System.out.println("Creating instance of class A with the A() constructor:"); A aInstance1 = new A(); System.out.println("aInstance1 was just born: " + aInstance1.toString()); @@ -129,8 +138,173 @@ public String toString() { C cInstance2 = new C("some string"); System.out.println("cInstance2 was just born: " + cInstance2.toString()); + System.out.println("\n/* END OF DEBUGGING CONSTRUCTORS */\n"); + }/* END OF DEBUGGING CONSTRUCTORS */ + + {/* SECTION FOR PLAYING WITH OVERLOADING METHODS */ + + System.out.println("\n/* SECTION FOR PLAYING WITH OVERLOADING METHODS */\n"); + + //Есть 3 перегруженных метода, которые принимают Object List и ArrayList. + // Мы вызываем функцию с параметром null. Какой метод выполнится? + + class A { + + void method(ObjectList objList) { + System.out.println("Method(ObjectList) is running ..."); + } + + void method(ArrayList arrList) { + System.out.println("Method(ArrayList) is running ..."); + } + + void method(ObjectList objList, ArrayList arrList) { + System.out.println("Method(ObjectList,ArrayList) is running ..."); + } + } + + A a = new A(); + ObjectList ol = null; + ArrayList al = null; + + a.method(ol); + a.method(al); + a.method(ol, al); + + System.out.println("\n/* END OF DEBUGGING OVERLOADING METHODS */\n"); + + }/* END OF DEBUGGING OVERLOADING METHODS */ + + + {/* SECTION FOR PLAYING WITH BINDING METHODS */ + + System.out.println("\n/* SECTION FOR PLAYING WITH BINDING METHODS */\n"); + + class Base { + void method() { + System.out.println("The version of method() declared in class Base is running ..."); + } + + void subtleMethod( int par ) { + System.out.println("The version of subtleMethod(int par=" + par + ") declared in class Base is running ..."); + } + } + + class Derived extends Base { + void method() { + System.out.println("The version of method() declared in class Derived is running ..."); + } + + void subtleMethod( byte par ) { + System.out.println("The version of subtleMethod(byte par=0b" + Integer.toBinaryString(par) + "=" + par + ") declared in class Derived is running ..."); + } + } + + // Type of reference variable instance1 is --> Base ( INFO FOR COMPILER = for early binding ) + // Type of the created referenced instance/object is --> Base ( INFO FOR JVM = for late binding ) + Base instanceBB = new Base(); + + // Type of reference variable instance2 is --> Base! ( INFO FOR COMPILER = for early binding ) + // Type of the created referenced instance/object is --> Derived ( INFO FOR JVM = for late binding ) + Base instanceBD = new Derived(); + + // Type of reference variable instance2 is --> Derived ( INFO FOR COMPILER = for early binding ) + // Type of the created referenced instance/object is --> Derived ( INFO FOR JVM = for late binding ) + Derived instanceDD = new Derived(); + + System.out.println("************** Overriding method() ****************"); + + System.out.println("\nBase instanceBB = new Base(); --> instanceBB.method():"); + instanceBB.method(); + + System.out.println("\nBase instanceBD = new Derived(); --> instanceBD.method():"); + instanceBD.method(); + + System.out.println("\nDerived instanceDD = new Derived(); --> instanceDD.method():"); + instanceDD.method(); + + System.out.println("\n************** Overloading subtlemethod() ****************\n"); + + int parII = 1; + int parIB = 0b0000010; + byte parBI = (byte) 3; + byte parBB = 0b0000100; + + System.out.println("1) Base instanceBB = new Base();"); + + System.out.println("\nint parII = 1; ( 0b" + Integer.toBinaryString(parII) + " )"); + System.out.println("Trying instanceBB.subtleMethod(parII):"); + instanceBB.subtleMethod(parII); + + System.out.println("\nint parIB = 0b0000010; ( " + Integer.toString(parIB) + " )"); + System.out.println("Trying instanceBB.subtleMethod(parIB):"); + instanceBB.subtleMethod(parIB); + + System.out.println("\nbyte parBI = (byte) 3; ( 0b" + Integer.toBinaryString(parBI) + " )"); + System.out.println("Trying instanceBB.subtleMethod(parBI):"); + instanceBB.subtleMethod(parBI); + + System.out.println("\nbyte parBB = 0b0000100; ( " + Integer.toString(parBB) + " )"); + System.out.println("Trying instanceBB.subtleMethod(parBB):"); + instanceBB.subtleMethod(parBB); + + System.out.println("\nRESUME:\n\tThe Base type of the reference instanceBB tells compiler that it has to look for the method subtleMethod() inside class Base."); + System.out.println("\tCompiler sees the only one version of the method subtleMethod() in the class Base so it decides to bind it with the call places in the code - early binding takes place. "); + System.out.println("\tThere is no late run-time binding because there is no other alternative of the body of the subtleMethod()."); + + + System.out.println("\n2) Base instanceBD = new Derived();"); + + System.out.println("\nint parII = 1; ( 0b" + Integer.toBinaryString(parII) + " )"); + System.out.println("Trying instanceBD.subtleMethod(parII):"); + instanceBD.subtleMethod(parII); + + System.out.println("\nint parIB = 0b0000010; ( " + Integer.toString(parIB) + " )"); + System.out.println("Trying instanceBD.subtleMethod(parIB):"); + instanceBD.subtleMethod(parIB); + + System.out.println("\nbyte parBI = (byte) 3; ( 0b" + Integer.toBinaryString(parBI) + " )"); + System.out.println("Trying instanceBD.subtleMethod(parBI):"); + instanceBD.subtleMethod(parBI); + + System.out.println("\nbyte parBB = 0b0000100; ( " + Integer.toString(parBB) + " )"); + System.out.println("Trying instanceBD.subtleMethod(parBB):"); + instanceBD.subtleMethod(parBB); + + System.out.println("\nRESUME:\n\tThe Base type of the reference instanceBD tells compiler that it should search for the method subtleMethod() inside class Base."); + System.out.println("\tCompiler sees the only one version of the method subtleMethod() in the class Base so it decides to bind it with the call places in the code - early binding takes place. "); + System.out.println("\tThere is no late run-time binding because there is no other alternative of the body of the subtleMethod()."); + + + System.out.println("\n3) Derived instanceDD = new Derived();"); + + System.out.println("\nint parII = 1; ( 0b" + Integer.toBinaryString(parII) + " )"); + System.out.println("Trying instanceBD.subtleMethod(parII):"); + instanceDD.subtleMethod(parII); + + System.out.println("\nint parIB = 0b0000010; ( " + Integer.toString(parIB) + " )"); + System.out.println("Trying instanceDD.subtleMethod(parIB):"); + instanceDD.subtleMethod(parIB); + + System.out.println("\nbyte parBI = (byte) 3; ( 0b" + Integer.toBinaryString(parBI) + " )"); + System.out.println("Trying instanceDD.subtleMethod(parBI):"); + instanceDD.subtleMethod(parBI); + + System.out.println("\nbyte parBB = 0b0000100; ( " + Integer.toString(parBB) + " )"); + System.out.println("Trying instanceDD.subtleMethod(parBB):"); + instanceDD.subtleMethod(parBB); + + System.out.println("\nRESUME:\n\tThe Derived type of the reference instanceDD tells compiler that it should search for the method subtleMethod() inside class Derived."); + System.out.println("\tCompiler sees two alternative versions of the method subtleMethod() in the class Derived - inherited from class Base and reloaded version."); + System.out.println("\tSo the compiler decides that it's not yet the time to bind the body of the subtleMethod() and so this time the early ( static ) binding is declined."); + System.out.println("\tDuring run-time JVM chooses proper version of the subtleMethod() body and binds it with the call place - the late ( dynamic ) binding occurs."); + + System.out.println("\n/* END OF DEBUGGING BINDING METHODS */\n"); + + }/* END OF DEBUGGING BINDING METHODS */ + System.exit(0); } From 5299e377d499ef15705f8f70b64199cdd1e55830 Mon Sep 17 00:00:00 2001 From: Yaro4Java Date: Mon, 30 Dec 2019 20:58:00 +0300 Subject: [PATCH 08/10] filling class SympleAuthorRepository and debugging its methods in main() --- .../java/com/epam/izh/rd/online/Main.java | 92 ++++++++------ .../com/epam/izh/rd/online/entity/Author.java | 2 +- .../repository/SimpleAuthorRepository.java | 119 ++++++++++++++++++ 3 files changed, 175 insertions(+), 38 deletions(-) create mode 100644 src/main/java/com/epam/izh/rd/online/repository/SimpleAuthorRepository.java diff --git a/src/main/java/com/epam/izh/rd/online/Main.java b/src/main/java/com/epam/izh/rd/online/Main.java index 37af731e..aa95d6d1 100644 --- a/src/main/java/com/epam/izh/rd/online/Main.java +++ b/src/main/java/com/epam/izh/rd/online/Main.java @@ -1,54 +1,19 @@ package com.epam.izh.rd.online; import com.epam.izh.rd.online.entity.Author; +import com.epam.izh.rd.online.repository.SimpleAuthorRepository; import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList; import com.sun.xml.internal.ws.addressing.WsaActionUtil; import org.springframework.util.Assert; import org.springframework.util.SocketUtils; +import java.time.LocalDate; import java.util.ArrayList; public class Main { public static void main(String[] args) { - {/* SECTION FOR DEBUGGING CLASS Author */ -// -// Author author1 = new Author(); -// -// author1.setName("Yaroslav"); -// author1.setCountry("Russia"); -// -// class FreakAuthor extends Author { -// public FreakAuthor(String name) { -// this.setName(name); -// } -// -// @Override -// public int hashCode() { -// return Object.class.hashCode(); -// } -// -// } -// -// FreakAuthor freak = new FreakAuthor("John"); -// -// System.out.println("author1.objectToString(): " + author1.objectToString()); -// System.out.println("author1.toString(): " + author1.toString()); -// System.out.println("\n" + "author1 is the following " + author1.toString()); -// -// System.out.println("\nHash code1 for author " + author1.getName() + " is " + author1.hashCode()); -// System.out.println("Hash code2 for author " + author1.getName() + " is " + author1.hashCode()); -// System.out.println("Hash code3 for author " + author1.getName() + " is " + author1.hashCode()); -// -// System.out.println("\nHash code1 for author " + freak.getName() + " is " + freak.hashCode()); -// System.out.println("Hash code2 for author " + freak.getName() + " is " + freak.hashCode()); -// System.out.println("Hash code3 for author " + freak.getName() + " is " + freak.hashCode()); -// System.out.println("author1.ToStringHash(): " + author1.ToStringHash()); - - }/* END OF DEBUGGING CLASS Author */ - - {/* SECTION FOR PLAYING WITH ASSERTIONS */ System.out.println("\n/* SECTION FOR PLAYING WITH ASSERTIONS */\n"); @@ -305,6 +270,59 @@ void subtleMethod( byte par ) { }/* END OF DEBUGGING BINDING METHODS */ + + {/* SECTION FOR DEBUGGING CLASSES */ + + System.out.println("\n/* SECTION FOR DEBUGGING CLASSES */\n"); + + Author author1 = new Author("Yaroslav", "Kozlov", LocalDate.of(1974,10,05), "Russia"); + Author author2 = new Author("James", "Bond", null, "UK"); + Author author3 = new Author("Wolfgang", "Mozart", LocalDate.of(1756,01,27), "Austria"); + + SimpleAuthorRepository rep4Authors = new SimpleAuthorRepository(); + + System.out.println("author1.toString(): " + author1.toString()); + System.out.println("author2.toString(): " + author2.toString()); + System.out.println("author3.toString(): " + author3.toString()); + + System.out.println("\nNumber of authors saved in repository is " + rep4Authors.count()); + + System.out.println("\nSaving author1 in repository"); + rep4Authors.save(author1); + System.out.println("Number of authors saved in repository is " + rep4Authors.count()); + + System.out.println("\nSaving author2 in repository"); + rep4Authors.save(author2); + System.out.println("Number of authors saved in repository is " + rep4Authors.count()); + + System.out.println("\nSaving author3 in repository"); + rep4Authors.save(author3); + System.out.println("Number of authors saved in repository is " + rep4Authors.count()); + + Author found; + found = rep4Authors.findByFullName("James", "Bond"); + System.out.println("\nIs James Bond in repository? " + (found == null ? "No: " : "Yes: ") + found); + found = rep4Authors.findByFullName("Vasya", "Pupkin"); + System.out.println("Is Vasya Pupkin in repository? " + (found == null ? "No: " : "Yes: ") + found); + + Author vasya = new Author("Vasya","Pupkin",null, null); + System.out.println("\nSaving author Vasya Pupkin in repository"); + rep4Authors.save(vasya); + System.out.println("Number of authors saved in repository is " + rep4Authors.count()); + + found = rep4Authors.findByFullName("Vasya", "Pupkin"); + System.out.println("Is Vasya Pupkin in repository? " + (found == null ? "No: " : "Yes: ") + found); + + System.out.println("\nRemoving author Vasya Pupkin from repository"); + rep4Authors.remove(vasya); + System.out.println("Number of authors saved in repository is " + rep4Authors.count()); + found = rep4Authors.findByFullName("Vasya", "Pupkin"); + System.out.println("Is Vasya Pupkin in repository? " + (found == null ? "No: " : "Yes: ") + found); + + System.out.println("\n/* END OF DEBUGGING CLASSES */\n"); + + }/* END OF DEBUGGING CLASSES */ + System.exit(0); } diff --git a/src/main/java/com/epam/izh/rd/online/entity/Author.java b/src/main/java/com/epam/izh/rd/online/entity/Author.java index ce2772ee..a1ffa38c 100644 --- a/src/main/java/com/epam/izh/rd/online/entity/Author.java +++ b/src/main/java/com/epam/izh/rd/online/entity/Author.java @@ -91,7 +91,7 @@ public int hashCode() { @Override public String toString() { - return "instance of class Author: { " + + return "instance of class Author = { " + "name='" + name + '\'' + ", lastName='" + lastName + '\'' + ", birthdate=" + birthdate + diff --git a/src/main/java/com/epam/izh/rd/online/repository/SimpleAuthorRepository.java b/src/main/java/com/epam/izh/rd/online/repository/SimpleAuthorRepository.java new file mode 100644 index 00000000..8d6cb0e7 --- /dev/null +++ b/src/main/java/com/epam/izh/rd/online/repository/SimpleAuthorRepository.java @@ -0,0 +1,119 @@ +package com.epam.izh.rd.online.repository; + +import com.epam.izh.rd.online.entity.Author; + +import java.util.Arrays; + +/** + * Класс SimpleAuthorRepository репозитория для хранения данных об авторах. + * + * Необходимо: + * 1) Имплементировать в данном классе интерфейс AuthorRepository + * 2) Добавить все методы интерфейса (пока можно не писать реализацию) + * 3) Добавить приватное поле "Author[] authors" для хранения авторов + * 4) Инициалазировать его пустым массивом + * 5) Написать в классе SimpleAuthorRepository реализацию для всех методов (коллекции не используем, работаем только с массивами) + */ +public class SimpleAuthorRepository implements AuthorRepository { + + private Author[] authors = {}; + private int counter = 0; + + /** + * Метод должен сохранять автора в массив authors. + * Массив при каждом сохранении должен увеличиваться в размере ровно на 1. + * То есть он ровно того размера, сколько сущностей мы в него сохранили. + *

+ * Если на вход для сохранения приходит автор, который уже есть в массиве (сохранен), то автор не сохраняется и + * метод возвращает false. + *

+ * Можно сравнивать только по полному имени (имя и фамилия), считаем, что двух авторов + * с одинаковыми именем и фамилией быть не может. + * Подсказка - можно использовать для проверки метод findByFullName. + *

+ * Если сохранение прошло успешно, метод должен вернуть true. + */ + @Override + public boolean save(Author author) { + + if (findByFullName(author.getName(), author.getLastName()) != null) { + return false; + } else { + + Author[] temp; + temp = authors; + authors = new Author[counter + 1]; + + for (int i = 0; i < counter; i++) { + authors[i] = temp[i]; + } + + authors[counter++] = author; + return true; + } + } + + /** + * Метод должен находить в массиве authors автора по имени и фамилии (считаем, что двух авторов + * с одинаковыми именем и фамилией быть не может.) + *

+ * Если автор с таким именем и фамилией найден - возвращаем его, если же не найден, метод должен вернуть null. + */ + @Override + public Author findByFullName(String name, String lastname) { + + if (authors.length == 0) { + return null; + } + + for(Author a : authors) { + if ((a.getName() == name) && (a.getLastName() == lastname)) { + return a; + } + } + + return null; + } + + /** + * Метод должен удалять автора из массива authors, если он там имеется. + * Автора опять же, можно определять только по совпадению имении и фамилии. + *

+ * Важно: при удалении автора из массива размер массива должен уменьшиться! + * То есть, если мы сохранили 2 авторов и вызвали count() (метод ниже), то он должен вернуть 2. + * Если после этого мы удалили 1 автора, метод count() должен вернуть 1. + *

+ * Если автор был найден и удален, метод должен вернуть true, в противном случае, если автор не был найден, метод + * должен вернуть false. + */ + @Override + public boolean remove(Author author) { + + if (findByFullName(author.getName(), author.getLastName()) == null) { + return false; + } else { + + Author[] temp; + temp = authors; + authors = new Author[counter - 1]; + + for (int i = 0, k = 0; i < counter; i++) { + if(temp[i] == author) { + continue; + } + authors[k++] = temp[i]; + } + + counter--; + return true; + } + } + + /** + * Метод возвращает количество сохраненных сущностей в массиве authors. + */ + @Override + public int count() { + return counter; + } +} From 385acac536758fd3e7ae4632d27e0be8a9515872 Mon Sep 17 00:00:00 2001 From: Yaro4Java Date: Tue, 31 Dec 2019 17:12:14 +0300 Subject: [PATCH 09/10] filling class SimpleSchoolBookRepository and debugging its methods in main() --- .../java/com/epam/izh/rd/online/Main.java | 61 ++++++++ .../com/epam/izh/rd/online/entity/Author.java | 12 -- .../com/epam/izh/rd/online/entity/Book.java | 6 +- .../epam/izh/rd/online/entity/SchoolBook.java | 9 +- .../repository/SimpleAuthorRepository.java | 2 +- .../SimpleSchoolBookRepository.java | 132 ++++++++++++++++++ .../izh/rd/online/service/BookService.java | 2 +- .../online/service/SimpleAuthorService.java | 65 +++++++++ .../service/SimpleSchoolBookService.java | 103 ++++++++++++++ 9 files changed, 374 insertions(+), 18 deletions(-) create mode 100644 src/main/java/com/epam/izh/rd/online/repository/SimpleSchoolBookRepository.java create mode 100644 src/main/java/com/epam/izh/rd/online/service/SimpleAuthorService.java create mode 100644 src/main/java/com/epam/izh/rd/online/service/SimpleSchoolBookService.java diff --git a/src/main/java/com/epam/izh/rd/online/Main.java b/src/main/java/com/epam/izh/rd/online/Main.java index aa95d6d1..4b539e80 100644 --- a/src/main/java/com/epam/izh/rd/online/Main.java +++ b/src/main/java/com/epam/izh/rd/online/Main.java @@ -1,7 +1,9 @@ package com.epam.izh.rd.online; import com.epam.izh.rd.online.entity.Author; +import com.epam.izh.rd.online.entity.SchoolBook; import com.epam.izh.rd.online.repository.SimpleAuthorRepository; +import com.epam.izh.rd.online.repository.SimpleSchoolBookRepository; import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList; import com.sun.xml.internal.ws.addressing.WsaActionUtil; import org.springframework.util.Assert; @@ -275,6 +277,8 @@ void subtleMethod( byte par ) { System.out.println("\n/* SECTION FOR DEBUGGING CLASSES */\n"); + System.out.println("********** Working with authors repository **********\n"); + Author author1 = new Author("Yaroslav", "Kozlov", LocalDate.of(1974,10,05), "Russia"); Author author2 = new Author("James", "Bond", null, "UK"); Author author3 = new Author("Wolfgang", "Mozart", LocalDate.of(1756,01,27), "Austria"); @@ -319,6 +323,63 @@ void subtleMethod( byte par ) { found = rep4Authors.findByFullName("Vasya", "Pupkin"); System.out.println("Is Vasya Pupkin in repository? " + (found == null ? "No: " : "Yes: ") + found); + System.out.println("\n********** Working with books repository **********\n"); + + SchoolBook book1 = new SchoolBook(250, "The hound of the Baskervilles", "Arthur", "Conan Doyle", null); + SchoolBook book2 = new SchoolBook(300, "The hound of the Baskervilles", "Arthur", "Doyle", null); + SchoolBook book3 = new SchoolBook(1000, "Short stories", "James", "Bond", null); + + SimpleSchoolBookRepository rep4Books = new SimpleSchoolBookRepository(); + + System.out.println("book1.toString(): " + book1.toString()); + System.out.println("book2.toString(): " + book2.toString()); + System.out.println("book3.toString(): " + book3.toString()); + + System.out.println("\nNumber of books saved in repository is " + rep4Books.count()); + + System.out.println("\nSaving book1 in repository"); + rep4Books.save(book1); + System.out.println("Number of books saved in repository is " + rep4Books.count()); + + System.out.println("\nSaving book2 in repository"); + rep4Books.save(book2); + System.out.println("Number of books saved in repository is " + rep4Books.count()); + + System.out.println("\nSaving book3 in repository"); + rep4Books.save(book3); + System.out.println("Number of books saved in repository is " + rep4Books.count()); + + SchoolBook[] foundBooks; + foundBooks = rep4Books.findByName("The hound of the Baskervilles"); + System.out.println("\nIs \"The hound of the Baskervilles\" in repository? " + (foundBooks.length == 0 ? "No books with such a title!" : "Yes: 1 of " + foundBooks.length + " is an " + foundBooks[0].toString() )); + + SchoolBook vasyasBook = new SchoolBook(500, "Memoirs", "Vasya", "Pupkin", null); + + foundBooks = rep4Books.findByName("Memoirs"); + System.out.println("\nIs \"Memoirs\" in repository? " + (foundBooks.length == 0 ? "No books with such a title!" : "Yes: 1 of " + foundBooks.length + " is an " + foundBooks[0].toString() )); + + System.out.println("\nSaving the book \"Memoirs\" by Vasya Pupkin in repository"); + rep4Books.save(vasyasBook); + System.out.println("Number of books saved in repository is " + rep4Books.count()); + + foundBooks = rep4Books.findByName("Memoirs"); + System.out.println("\nIs \"Memoirs\" in repository? " + (foundBooks.length == 0 ? "No books with such a title!" : "Yes: 1 of " + foundBooks.length + " is an " + foundBooks[0].toString() )); + + System.out.println("\nRemoving \"Memoirs\" from repository"); + rep4Books.removeByName("Memoirs"); + System.out.println("Number of books saved in repository is " + rep4Books.count()); + + System.out.println("\nRemoving \"The hound of the Baskervilles\" from repository"); + rep4Books.removeByName("The hound of the Baskervilles"); + System.out.println("Number of books saved in repository is " + rep4Books.count()); + + foundBooks = rep4Books.findByName("Memoirs"); + System.out.println("\nIs \"Memoirs\" in repository? " + (foundBooks.length == 0 ? "No books with such a title!" : "Yes: 1 of " + foundBooks.length + " is an " + foundBooks[0].toString() )); + + foundBooks = rep4Books.findByName("The hound of the Baskervilles"); + System.out.println("\nIs \"The hound of the Baskervilles\" in repository? " + (foundBooks.length == 0 ? "No books with such a title!" : "Yes: 1 of " + foundBooks.length + " is an " + foundBooks[0].toString() )); + + System.out.println("\n/* END OF DEBUGGING CLASSES */\n"); }/* END OF DEBUGGING CLASSES */ diff --git a/src/main/java/com/epam/izh/rd/online/entity/Author.java b/src/main/java/com/epam/izh/rd/online/entity/Author.java index a1ffa38c..e8a37df2 100644 --- a/src/main/java/com/epam/izh/rd/online/entity/Author.java +++ b/src/main/java/com/epam/izh/rd/online/entity/Author.java @@ -98,16 +98,4 @@ public String toString() { ", country='" + country + '\'' + " }"; } - - // Original method toString() - public String objectToString() { - return super.toString(); - } - - - public String ToStringHash() { - return Object.class.hashCode() + " ( " + Integer.toHexString(Object.class.hashCode()) + " )"; - - } - } diff --git a/src/main/java/com/epam/izh/rd/online/entity/Book.java b/src/main/java/com/epam/izh/rd/online/entity/Book.java index 8d029838..c537342d 100644 --- a/src/main/java/com/epam/izh/rd/online/entity/Book.java +++ b/src/main/java/com/epam/izh/rd/online/entity/Book.java @@ -64,7 +64,9 @@ public int hashCode() { @Override public String toString() { - return super.toString(); + return "instance of class Book = { " + + "numberOfPages=" + numberOfPages + + ", name='" + name + '\'' + + "' }"; } - } diff --git a/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java b/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java index 1419df35..283f5cdc 100644 --- a/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java +++ b/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java @@ -84,7 +84,12 @@ public int hashCode() { @Override public String toString() { - return super.toString(); + return "instance of class SchoolBook = { " + + "Number of pages = " + this.getNumberOfPages() + + ", Name='" + this.getName() + '\'' + + ", authorName='" + authorName + '\'' + + ", authorLastName='" + authorLastName + '\'' + + ", publishDate=" + publishDate + + "' }"; } - } diff --git a/src/main/java/com/epam/izh/rd/online/repository/SimpleAuthorRepository.java b/src/main/java/com/epam/izh/rd/online/repository/SimpleAuthorRepository.java index 8d6cb0e7..3bbc5dda 100644 --- a/src/main/java/com/epam/izh/rd/online/repository/SimpleAuthorRepository.java +++ b/src/main/java/com/epam/izh/rd/online/repository/SimpleAuthorRepository.java @@ -12,7 +12,7 @@ * 2) Добавить все методы интерфейса (пока можно не писать реализацию) * 3) Добавить приватное поле "Author[] authors" для хранения авторов * 4) Инициалазировать его пустым массивом - * 5) Написать в классе SimpleAuthorRepository реализацию для всех методов (коллекции не используем, работаем только с массивами) + * 5) Написать реализацию для всех методов (коллекции не используем, работаем только с массивами) */ public class SimpleAuthorRepository implements AuthorRepository { diff --git a/src/main/java/com/epam/izh/rd/online/repository/SimpleSchoolBookRepository.java b/src/main/java/com/epam/izh/rd/online/repository/SimpleSchoolBookRepository.java new file mode 100644 index 00000000..d18e8918 --- /dev/null +++ b/src/main/java/com/epam/izh/rd/online/repository/SimpleSchoolBookRepository.java @@ -0,0 +1,132 @@ +package com.epam.izh.rd.online.repository; + +import com.epam.izh.rd.online.entity.Author; +import com.epam.izh.rd.online.entity.SchoolBook; + +/** + * Класс SimpleSchoolBookRepository репозитория для хранения данных о книгах + *

+ * Необходимо: + * 1) Имплементировать интерфейс BookRepository ( с указанием дженерика ) + * 2) Добавить все методы (пока можно не писать реализацию) + * 3) Добавить приватное поле "SchoolBook[] schoolBooks" для хранения школьных книг + * 4) Инициалазировать его пустым массивом + * 5) Написать реализацию для всех методов (коллекции не используем, работаем только с массивами) + */ +public class SimpleSchoolBookRepository implements BookRepository { + + private SchoolBook[] schoolBooks = {}; + int counter = 0; + + /** + * Метод должен сохранять школьную книгу в массив schoolBooks. + * Массив при каждом сохранении должен увеличиваться в размере ровно на 1. + * То есть он ровно того размера, сколько сущностей мы в него сохранили. + *

+ * Одну и ту же книгу МОЖНО сохранить в массиве несколько раз, проверки на то, что такая книга уже сохранена, делать не нужно. + *

+ * Если сохранение прошло успешно, метод должен вернуть true. + */ + @Override + public boolean save(SchoolBook book) { + + if (book == null) { + return false; + } else { + + SchoolBook[] temp; + temp = schoolBooks; + schoolBooks = new SchoolBook[counter + 1]; + + for (int i = 0; i < counter; i++) { + schoolBooks[i] = temp[i]; + } + + schoolBooks[counter++] = book; + return true; + } + } + + /** + * Метод должен находить в массиве schoolBooks все книги по имени. + *

+ * Если книги найдены - метод должен их вернуть. + * Если найденных по имени книг нет, должен вернуться пустой массив. + */ + @Override + public SchoolBook[] findByName(String name) { + + int match = 0; + + // Counting number of books in repository with the same given name + for (SchoolBook b : schoolBooks) { + if(b.getName() == name) { + match++; + } + } + + if (match == 0) { // If no matching, return empty SchoolBook array + return new SchoolBook[0]; + } else { // If there is something, add books with same name to special temp[] array and return it + + SchoolBook[] temp = new SchoolBook[match]; + + for (int i = 0, k = 0; i < counter; i++) { + if (schoolBooks[i].getName() == name) { + temp[k++] = schoolBooks[i]; + } + } + + return temp; + } + } + + /** + * Метод должен удалять книги из массива schoolBooks по названию. + * Если книг с одинаковым названием в массиве несколько, метод должен удалить их все. + *

+ * Важно: при удалении книги из массива размер массива должен уменьшиться! + * То есть, если мы сохранили 2 разные книги и вызвали count() (метод ниже), то он должен вернуть 2. + * Если после этого мы удалили 1 книгу, метод count() должен вернуть 1. + *

+ * Если хотя бы одна книга была найдена и удалена, метод должен вернуть true, в противном случае, + * если книга не была найдена, метод должен вернуть false. + */ + @Override + public boolean removeByName(String name) { + + int match = 0; + + // Counting number of books in repository with the same given name + for (SchoolBook b : schoolBooks) { + if(b.getName() == name) { + match++; + } + } + + if (match == 0) { // If no matching, return false + return false; + } else { // If there is something, create new schoolBooks[] array without books with the given name and return true + + SchoolBook[] temp = new SchoolBook[counter - match]; + + for (int i = 0, k = 0; i < counter; i++) { + if (schoolBooks[i].getName() != name) { + temp[k++] = schoolBooks[i]; + } + } + + schoolBooks = temp; + counter = schoolBooks.length; + return true; + } + } + + /** + * Метод возвращает количество сохраненных сущностей в массиве schoolBooks. + */ + @Override + public int count() { + return counter; + } +} diff --git a/src/main/java/com/epam/izh/rd/online/service/BookService.java b/src/main/java/com/epam/izh/rd/online/service/BookService.java index e221033b..1dfdc577 100644 --- a/src/main/java/com/epam/izh/rd/online/service/BookService.java +++ b/src/main/java/com/epam/izh/rd/online/service/BookService.java @@ -4,7 +4,7 @@ import com.epam.izh.rd.online.entity.Book; /** - * Интерфейс сервиса для выполнения бизнес логики при работе с книга и авторами и взаимодействием с + * Интерфейс сервиса для выполнения бизнес логики при работе с книгами и авторами и взаимодействием с * репозиторием для книг BookRepository и сервисом для авторов AuthorService. *

* Необходимо: diff --git a/src/main/java/com/epam/izh/rd/online/service/SimpleAuthorService.java b/src/main/java/com/epam/izh/rd/online/service/SimpleAuthorService.java new file mode 100644 index 00000000..c2298c98 --- /dev/null +++ b/src/main/java/com/epam/izh/rd/online/service/SimpleAuthorService.java @@ -0,0 +1,65 @@ +package com.epam.izh.rd.online.service; + +import com.epam.izh.rd.online.entity.Author; +import com.epam.izh.rd.online.repository.AuthorRepository; + +/** + * Класс SimpleAuthorService сервиса для выполнения бизнес логики при работе с авторами и взаимодействием с + * репозиторием для авторов AuthorRepository. + *

+ * Необходимо: + * 1) Имплементировать интерфейс AuthorService + * 2) Добавить все методы (пока можно не писать реализацию) + * 3) Добавить в SimpleAuthorService приватное поле "AuthorRepository authorRepository" - это репозиторий к котормоу + * вы будете обращаться в методах + * 4) Создать дефолтный конструтор (без параметров) + * 5) Создать конструтор с параметром AuthorRepository authorRepository (который будет устанвливать в поле authorRepository значение) + * 6) Написать реализацию для всех методов + */ +public class SimpleAuthorService implements AuthorService { + + private AuthorRepository authorRepository; + + public SimpleAuthorService() { + } + + public SimpleAuthorService(AuthorRepository authorRepository) { + this.authorRepository = authorRepository; + } + + /** + * Метод должен сохранять автора. + * По факту, он просто обращается к репозиторию с авторами и вызывает аналогичный метод, псоле чего возвращает результат. + */ + @Override + public boolean save(Author author) { + return this.authorRepository.save(author); + } + + /** + * Метод должен находить автора по имени и фамилии. + * По факту, он просто обращается к репозиторию с авторами и вызывает аналогичный метод, псоле чего возвращает результат. + */ + @Override + public Author findByFullName(String name, String lastname) { + return this.authorRepository.findByFullName(name, lastname); + } + + /** + * Метод должен удалять автора. + * По факту, он просто обращается к репозиторию с авторами и вызывает аналогичный метод, псоле чего возвращает результат.. + */ + @Override + public boolean remove(Author author) { + return this.authorRepository.remove(author); + } + + /** + * Метод считать количество сохраненных авторов на текущий момент. + * По факту, он просто обращается к репозиторию с авторами и вызывает аналогичный метод, псоле чего возвращает результат. + */ + @Override + public int count() { + return this.authorRepository.count(); + } +} diff --git a/src/main/java/com/epam/izh/rd/online/service/SimpleSchoolBookService.java b/src/main/java/com/epam/izh/rd/online/service/SimpleSchoolBookService.java new file mode 100644 index 00000000..0cb8a716 --- /dev/null +++ b/src/main/java/com/epam/izh/rd/online/service/SimpleSchoolBookService.java @@ -0,0 +1,103 @@ +package com.epam.izh.rd.online.service; + +import com.epam.izh.rd.online.entity.Author; +import com.epam.izh.rd.online.entity.Book; +import com.epam.izh.rd.online.entity.SchoolBook; +import com.epam.izh.rd.online.repository.BookRepository; + +/** + * Класс SimpleSchoolBookService для выполнения бизнес логики при работе с книгами и авторами и взаимодействием с + * репозиторием для книг BookRepository и сервисом для авторов AuthorService. + *

+ * Необходимо: + * 1) Имплементировать интерфейс BookService + * 2) Добавить все методы (пока можно не писать реализацию) + * 3) Добавить приватное поле "BookRepository schoolBookBookRepository" - это репозиторий + * книг к которому вы будете обращаться в методах + * 4) Добавить приватное поле "AuthorService authorService" - это сервис для работы с авторами, к которому + * вы будете обращаться в методах + * 5) Создать дефолтный конструтор (без параметров) + * 6) Создать конструтор с параметрами "BookRepository schoolBookBookRepository, AuthorService authorService" + * (который будет устанвливать в поле schoolBookBookRepository и в поле authorService значения) + * 7) Написать реализацию для всех методов + */ +public class SimpleSchoolBookService implements BookService { + + private BookRepository schoolBookBookRepository; + private AuthorService authorService; + + public SimpleSchoolBookService() { + } + + public SimpleSchoolBookService(BookRepository schoolBookBookRepository, AuthorService authorService) { + this.schoolBookBookRepository = schoolBookBookRepository; + this.authorService = authorService; + } + + /** + * Метод должен сохранять книгу. + * + * Перед сохранением книги нужно проверить, сохранен ли такой автор в базе авторов. + * То есть вы должен взять имя и фамилию автора из книги и обратиться к сервису авторов и узнать о наличии такого автора. + * Напомню, что мы считаем, что двух авторов с одинаковыми именем и фамилией быть не может. + * + * Если такой автор сущесвует (сохранен) - значит можно сохранять и книгу. + * Если же такого автора в базе нет, значит книгу сохранять нельзя. + * + * Соответственно, если книга была успешно сохранена - метод возвращает true, если же книга не была сохранена - метод возвращает false. + */ + @Override + public boolean save(Book book) { + return false; + } + + /** + * Метод должен находить книгу по имени. + *

+ * По факту, он просто обращается к репозиторию с книгами и вызывает аналогичный метод, псоле чего возвращает результат. + */ + @Override + public Book[] findByName(String name) { + return this.schoolBookBookRepository.findByName(name); + } + + /** + * Метод должен находить количество сохраненных книг по конкретному имени книги. + */ + @Override + public int getNumberOfBooksByName(String name) { + return 0; + } + + /** + * Метод должен удалять все книги по имени. + *

+ * По факту, он просто обращается к репозиторию с книгами и вызывает аналогичный метод, псоле чего возвращает результат. + */ + @Override + public boolean removeByName(String name) { + return this.schoolBookBookRepository.removeByName(name); + } + + /** + * Метод должен возвращать количество всех книг. + *

+ * По факту, он просто обращается к репозиторию с книгами и вызывает аналогичный метод, псоле чего возвращает результат. + */ + @Override + public int count() { + return this.schoolBookBookRepository.count(); + } + + /** + * Метод должен возвращать автора книги по названию книги. + * + * То есть придётся сходить и в репозиторий с книгами, и в сервис авторов. + * + * Если такой книги не найдено, метод должен вернуть null. + */ + @Override + public Author findAuthorByBookName(String name) { + return null; + } +} From b972fa3d1064d9ffdcf05da0f989c42bb74c2dc2 Mon Sep 17 00:00:00 2001 From: Yaro4Java Date: Wed, 1 Jan 2020 02:30:03 +0300 Subject: [PATCH 10/10] filling classes for Services and debugging their methods in main() --- .../java/com/epam/izh/rd/online/Main.java | 33 +++++++++++++- .../SimpleSchoolBookRepository.java | 7 +-- .../service/SimpleSchoolBookService.java | 45 +++++++++++++++---- 3 files changed, 72 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/epam/izh/rd/online/Main.java b/src/main/java/com/epam/izh/rd/online/Main.java index 4b539e80..bd28b8eb 100644 --- a/src/main/java/com/epam/izh/rd/online/Main.java +++ b/src/main/java/com/epam/izh/rd/online/Main.java @@ -4,10 +4,11 @@ import com.epam.izh.rd.online.entity.SchoolBook; import com.epam.izh.rd.online.repository.SimpleAuthorRepository; import com.epam.izh.rd.online.repository.SimpleSchoolBookRepository; +import com.epam.izh.rd.online.service.SimpleAuthorService; +import com.epam.izh.rd.online.service.SimpleSchoolBookService; import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList; -import com.sun.xml.internal.ws.addressing.WsaActionUtil; import org.springframework.util.Assert; -import org.springframework.util.SocketUtils; + import java.time.LocalDate; import java.util.ArrayList; @@ -379,6 +380,34 @@ void subtleMethod( byte par ) { foundBooks = rep4Books.findByName("The hound of the Baskervilles"); System.out.println("\nIs \"The hound of the Baskervilles\" in repository? " + (foundBooks.length == 0 ? "No books with such a title!" : "Yes: 1 of " + foundBooks.length + " is an " + foundBooks[0].toString() )); + System.out.println("\n********** Using services ***********\n"); + + // Creating service with methods for authors repository + SimpleAuthorService ser4Authors = new SimpleAuthorService(rep4Authors); + + // Creating service with functionality to work with books taking in account given authors repository + SimpleSchoolBookService ser4Books = new SimpleSchoolBookService(rep4Books, ser4Authors); + + System.out.println("Number of books in storage is: " + ser4Books.count()); + System.out.println("Number of authors registered is: " + ser4Authors.count()); + + System.out.println("\nRecording author Vasya Pupkin into authors repository ..."); + rep4Authors.save(vasya); + System.out.println("Now the number of registered authors is: " + ser4Authors.count()); + + System.out.println("\nAdding 5 instances of the book \"Memoirs\" by Vasya Pupkin to book storage ..."); + for (int i=0; i < 5; i++) { + rep4Books.save(vasyasBook); + } + System.out.println("Now total number of books in the storage is: " + ser4Books.count()); + System.out.println("Number of book \"Memoirs\" in the storage is: " + ser4Books.getNumberOfBooksByName("Memoirs") + " of " + ser4Books.count()); + System.out.println("1st found \"Memoirs\" is: " + ser4Books.findByName("Memoirs")[0]); + System.out.println("The author of \"Memoirs\" is: " + ser4Books.findAuthorByBookName("Memoirs")); + + System.out.println("\nRemoving all (5) instances of the book \"Memoirs\" by Vasya Pupkin from the book storage ..."); + ser4Books.removeByName("Memoirs"); + System.out.println("Now total number of books in the storage is: " + ser4Books.count()); + System.out.println("Number of book \"Memoirs\" in the storage is: " + ser4Books.getNumberOfBooksByName("Memoirs") + " of " + ser4Books.count()); System.out.println("\n/* END OF DEBUGGING CLASSES */\n"); diff --git a/src/main/java/com/epam/izh/rd/online/repository/SimpleSchoolBookRepository.java b/src/main/java/com/epam/izh/rd/online/repository/SimpleSchoolBookRepository.java index d18e8918..2cd09fb8 100644 --- a/src/main/java/com/epam/izh/rd/online/repository/SimpleSchoolBookRepository.java +++ b/src/main/java/com/epam/izh/rd/online/repository/SimpleSchoolBookRepository.java @@ -30,9 +30,7 @@ public class SimpleSchoolBookRepository implements BookRepository { @Override public boolean save(SchoolBook book) { - if (book == null) { - return false; - } else { + try { SchoolBook[] temp; temp = schoolBooks; @@ -44,6 +42,9 @@ public boolean save(SchoolBook book) { schoolBooks[counter++] = book; return true; + + } catch (Exception e) { // If saving failed, return false + return false; } } diff --git a/src/main/java/com/epam/izh/rd/online/service/SimpleSchoolBookService.java b/src/main/java/com/epam/izh/rd/online/service/SimpleSchoolBookService.java index 0cb8a716..4d602ae8 100644 --- a/src/main/java/com/epam/izh/rd/online/service/SimpleSchoolBookService.java +++ b/src/main/java/com/epam/izh/rd/online/service/SimpleSchoolBookService.java @@ -1,7 +1,6 @@ package com.epam.izh.rd.online.service; import com.epam.izh.rd.online.entity.Author; -import com.epam.izh.rd.online.entity.Book; import com.epam.izh.rd.online.entity.SchoolBook; import com.epam.izh.rd.online.repository.BookRepository; @@ -21,7 +20,7 @@ * (который будет устанвливать в поле schoolBookBookRepository и в поле authorService значения) * 7) Написать реализацию для всех методов */ -public class SimpleSchoolBookService implements BookService { +public class SimpleSchoolBookService implements BookService { private BookRepository schoolBookBookRepository; private AuthorService authorService; @@ -38,7 +37,7 @@ public SimpleSchoolBookService(BookRepository schoolBookBookReposito * Метод должен сохранять книгу. * * Перед сохранением книги нужно проверить, сохранен ли такой автор в базе авторов. - * То есть вы должен взять имя и фамилию автора из книги и обратиться к сервису авторов и узнать о наличии такого автора. + * То есть вы должны взять имя и фамилию автора из книги и обратиться к сервису авторов и узнать о наличии такого автора. * Напомню, что мы считаем, что двух авторов с одинаковыми именем и фамилией быть не может. * * Если такой автор сущесвует (сохранен) - значит можно сохранять и книгу. @@ -47,17 +46,33 @@ public SimpleSchoolBookService(BookRepository schoolBookBookReposito * Соответственно, если книга была успешно сохранена - метод возвращает true, если же книга не была сохранена - метод возвращает false. */ @Override - public boolean save(Book book) { - return false; + public boolean save(SchoolBook book) { + + boolean isAuthorInRep; + + // Getting author's full name from the given book + String aName = book.getAuthorName(); + String aLastName = book.getAuthorLastName(); + + // Trying to find author in authors repository + isAuthorInRep = authorService.findByFullName(aName, aLastName) != null; + + if (isAuthorInRep) { // Author is in authors repository --> save the book in books repository and return true + schoolBookBookRepository.save(book); + return true; + } else { // If the author is not registered, return false + return false; + } } /** * Метод должен находить книгу по имени. *

* По факту, он просто обращается к репозиторию с книгами и вызывает аналогичный метод, псоле чего возвращает результат. + * */ @Override - public Book[] findByName(String name) { + public SchoolBook[] findByName(String name) { return this.schoolBookBookRepository.findByName(name); } @@ -66,7 +81,7 @@ public Book[] findByName(String name) { */ @Override public int getNumberOfBooksByName(String name) { - return 0; + return schoolBookBookRepository.findByName(name).length; // Size of the array of found books } /** @@ -98,6 +113,20 @@ public int count() { */ @Override public Author findAuthorByBookName(String name) { - return null; + + // Trying to find books with the given name + SchoolBook[] booksByName = schoolBookBookRepository.findByName(name); + + if (booksByName.length == 0) { // If there are no books with the given title, return null + return null; + } else { // If we've got books with the given title + + // Getting author's full name from the 1st found book + String xName = booksByName[0].getAuthorName(); + String xLastName = booksByName[0].getAuthorLastName(); + + // Now trying to find author of the book in authors repository and return the result (Author || null) + return authorService.findByFullName(xName, xLastName); + } } }