class A { class Dog { private String name; private String type; } }
Như vậy, việc sử dụng inner class đã phá vỡ quy tắc Single responsibility trong Solid, vậy khi nào dùng inner class là hợp lý nhất ạ
We want to connect the people who have knowledge to the people who need it, to bring together people with different perspectives so they can understand each other better, and to empower everyone to share their knowledge.
class A { class Dog { private String name; private String type; } }
Như vậy, việc sử dụng inner class đã phá vỡ quy tắc Single responsibility trong Solid, vậy khi nào dùng inner class là hợp lý nhất ạ
Inner class nên dùng khi các lớp inner này có liên quan mật thiết và bổ trợ cho lớp public, thường sẽ là các lớp private.
Ví dụ:
public class StringConverter { private stringToIntConverter = new StringToIntConverter(); private stringToLongConverter = new StringToLongConverter(); public T convert(String value, Class outType) { if (outType == int.class) { return stringToIntConverter.convert(value); } if (outType == long.class) { return stringToLongConverter.convert(value); } } private final class StringToIntConverter implements Converter { // logic } private final class StringToLongConverter implements Converter { // logic } }
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Input your email to receive reset password link, or if you remember your password, you can click