Advertisement
Guest User

Untitled

a guest
Feb 5th, 2016
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. package com.javarush.test.level23.lesson04.task02;
  2.  
  3. /* Inner 2
  4. В классе SuperUser метод getDescription должен учитывать страну и город, т.е. возвращать результат аналогичный следующему:
  5. My name is George. I'm from the USA, Seattle.
  6. Используйте возможности иннер класса.
  7. */
  8. public class Solution
  9. {
  10. private String country;
  11. private String city;
  12.  
  13. public Solution(String country, String city)
  14. {
  15. this.country = country;
  16. this.city = city;
  17. }
  18.  
  19. /*т.к. модификатор иннер класса private, то чтобы вызвать метод getDescription из другого внешнего класса,
  20. нужно обернуть его вызов в какой-то public метод*/
  21. public String getDescriptionOfUser(String name)
  22. {
  23. return getTrickyUser(name).getDescription();
  24. }
  25.  
  26. public SuperUser getTrickyUser(String name)
  27. {
  28. return new SuperUser(name);
  29. }
  30.  
  31. private class SuperUser
  32. {
  33. private String name;
  34.  
  35. //доступ к этому методу возможен только внутри класса Solution, т.к. модификатор иннер класса private
  36. public SuperUser(String name)
  37. {
  38. this.name = name;
  39. }
  40.  
  41. //доступ к этому методу возможен только внутри класса Solution, т.к. модификатор иннер класса private
  42. public String getDescription()
  43. {
  44. return String.format("My name is %s. I'm from %s, %s.", this.name, Solution.this.country, Solution.this.city);
  45. }
  46. }
  47.  
  48. public static void main(String[] args)
  49. {
  50. Solution solution = new Solution("the USA", "Seattle");
  51. //внутри класса Solution (а сейчас мы внутри) к методу getDescription можно обращаться обоими способами
  52. System.out.println(solution.getTrickyUser("George").getDescription());
  53. //а из любого другого внешнего класса только так:
  54. System.out.println(solution.getDescriptionOfUser("George"));
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement