public class MyClass{...}
class MyHelper{...}
Enclosing Class.Nested Class (MyClass.MyHelper)
**import (package name) .MyClass.MyHelper;
var h = new MyHelper ();
//MyHelper definition under class block
public class MyClass {
//Definition of static member class
//Members cannot be seen from outside My Class
private static class MyHelper {
public void show() {
System.out.println("Nested class is running!");
}
}
public void run() {
//MyHelper can be called inside the enclosing
var helper = new MyHelper();
helper.show();
}
}
public class NestBasic {
public static void main(String[] args) {
var c = new MyClass();
c.run();
//MyHelpe is invisible from outside MyClass
// var h = new MyClass.MyHelper(); //error!
}
}
class MyClass {
private String str1 = "Enclosing instance";
private static String str2 = "Enclosing class";
private class MyHelper {
private String str1 = "Nested instance";
private static final String str2 = "Nested class";
public void show() {
//Inner class has a reference to the enclosing object
//MyClass.Accessable with this
System.out.println(MyClass.this.str1); //Enclosing instance
System.out.println(MyClass.str2); //Enclosing class
}
}
public void run() {
//An instance of the inner class is created by the instance method of the enclosing class.
var helper = new MyHelper();
helper.show();
//Access inner class from enclosing object
System.out.println(helper.str1); //Nested instance
System.out.println(MyHelper.str2); //Nested class
}
}
public class NestedAccess {
public static void main(String[] args) {
var c = new MyClass();
c.run();
}
}
java:java.util.AbstractList.java
package java.util;
import java.util.function.Consumer;
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
//...Omission
/*Iterators
No need to show the internal implementation of the Itr class
It would be nice if the Iterators type, which is the implementation source, could be seen from the outside.
The return value of the iterator method is an Iterator type
*/
public Iterator<E> iterator() {
return new Itr();
}
//...Omission
/*Inner class
Implement an iterator that accesses the private field in the list and accesses the subordinate elements in order
Iterator is defined separately as an Iterator implementation class
*/
private class Itr implements Iterator<E> {
//...Omission
}
//...Omission
}
new base class (argument, ...) {class body}
**
new View.OnClickListener(){
//Event listener registration
btn.setOnClickListener(
//Anonymous class(Event listener)Definition
new View.OnClickListener(){
//btn Click to display current time in txt
@Override
public void onClick(View view){
TextView txt = findViewById(R.id.txtResult);
txt.setText(LocalDateTime.now().toString());
}
}
);
Recommended Posts