Thứ Bảy, 21 tháng 4, 2012

Bài 16 - Lớp nội (lớp nằm trong lớp khác)



public class TestProgram
{
                static int currentCount;
                static class Apple
                {
                                int weight;
                                public Apple(int weight)
                                {
                                                this.weight=weight;
                                                currentCount++;
                                }
                                public int Weight()
                                {
                                                return weight;
                                }
                }
                public static void main(String args[])
                {
                                Apple a=new Apple(12);//khoi tao 1 quả tao nang 12kg
                                System.out.print(a.Weight());
                }
}

Ở đây ta thấy lớp nội Apple trong lớp TestProgram, khi biên dịch Java sẽ làm xuất hiện 2 file là TestProgram.class và TestProgram$Apple.class. Ưu điểm khi sử dụng lớp nội là:
- thể hiện tính đóng gói cao


- các lớp nội có thể truy xuất trực tiếp các biến của lớp cha
Lưu ý là lớp nội khác với các lớp mà nằm chung một file, ví dụ như tập tin MainClass.java dưới đây

public class MainClass
{
}
class Subclass
{
}


Khi biên dịch nó sẽ tạo ra 2 file là MainClass.class và Subclass.class 


nguồn: http://forum.cuasotinhoc.vn
Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...

0 nhận xét

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

 
© Download do an khoa luan tai lieu
Designed by BlogThietKe Cooperated with Duy Pham
Released under Creative Commons 3.0 CC BY-NC 3.0
Posts RSSComments RSS
Back to top