Java的匿名物件/方法
阿新 • • 發佈:2019-01-10
匿名物件就是沒有明確給出名稱的物件.一般匿名物件只使用一次,而且匿名物件只在堆記憶體中開闢空間,而不存在棧記憶體的引用.
class Person{ private String name ; private int age ; public Person(String n,int a){ // 宣告構造方法,為類中的屬性初始化 this.setName(n) ; this.setAge(a) ; } public void setName(String n){ name = n ; } public void setAge(int a){ if(a>0&&a<150){ age = a ; } } public String getName(){ return name ; } public int getAge(){ return age ; } public void tell(){ System.out.println("姓名:" + this.getName() + ";年齡:" + this.getAge()) ; } }; public class NonameDemo01{ public static void main(String args[]){ new Person("張三",30).tell() ; } };
其中new Person("張三",30).tell() ;就是生成匿名物件
同理,匿名方法也是如此,不是物件引用方法,而是new 一個新方法.