티스토리 뷰
1. Anonymous class has no name so, It allows a base class to implement without a name.
2. It is often used for overriding the methods of a class or interface.
3. It can be used only once.
Person p = new Person(); // semi-colon 을 지우고 중괄호를 열어서 코드를 시작해준다.
public void greeting() // greeting method를 overriding해준다.
// overriding은 subclass에서만 사용가능하기에 p가 person class의 자식클래스에서 왔다는 것을 알수있다.
// 이곳에서는 Person의 subclass를 찾아볼수가 없는데 그래서 anonymous class 즉, 익명클래스라고 불린다.
// overriding 이나 interface 처럼 subclass 에서 구현되어져야하는 곳에서 익명클래스는 주로 쓰이게된다.
Example code
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 29 30 31 32 33 34 35 36 37 38 39 | //1. implementing an anonymous class through a base class class Person { public void greeting(){ System.out.println("Hello"); } } //2. implementing an anonymous class through an interface // The interface is not allowed to implement the actual code inside interface Utility{ void showInfo(); } public class Main{ public static void main(String[] args){ //p is instantiated from the subclass of Person class Person p = new Person(){//because overriding can only be written in subclass public void greeting(){ System.out.println("Hello anonymous class"); } }; p.greeting(); // generally, the interface needs another class to implement. // but by using an anonymous class, it can be instantiated. Utility util = new Utility() { @Override public void showInfo() { System.out.println("It's implemented by an interface"); } }; util.showInfo(); } } | cs |
Result
1 2 3 | Hello anonymous class It's implemented by an interface | cs |
Reference
https://www.youtube.com/watch?v=Yyr451RBB6g
'JAVA' 카테고리의 다른 글
compareTo method in Java (0) | 2019.02.21 |
---|---|
Reference Data Type in Java (0) | 2019.02.20 |
What's the difference between two different List declaration? (0) | 2019.02.02 |
Upcasting (Object type casting) in java (0) | 2019.01.30 |
String class in Java (0) | 2019.01.20 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- hackerrank javascript
- code refactoring
- string class in java
- equals()
- hackerrank solution
- Javascript Algorithm
- C++
- compareTo()
- ... in Javascript
- hackerrank javascript solution
- math.max
- Collection Framework
- HashMap
- 프로그래머스 알고리즘문제
- easy javascript algorithm
- rest parameter
- easy algorithm
- math.abs
- algorithm
- 프로그래머스
- substring()
- hackerrank
- java
- 프로그래머스 알고리즘
- HackerRank Algorithm
- javascript
- Object type casting
- repeat()
- spring boot application
- 알고리즘
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 |
30 |
글 보관함