Java'da bir class içindeki property'leri (özellikleri) veya method'ları encapsülation yapma yöntemleri aşağıdaki gibidir :
Test a = new Test();Yukarıda T sınıfının a örneği yaratılmıştır. Aynı sınıftan istenildiği kadar instance yaratılabilir.
Test b = new Test(); Test c = new Test(); Test d = new Test();Yukarıda aynı class'tan birden çok instance yaratılmıştır. Eğer class'ın parametre alan bir kurucusu (constructor) varsa o kurucu kullanılabilir.
Test e=new Test(3);
button.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e){ System.out.println("Action!") } } )
public class Point{ private int x=0; private int y=0; public Point(int xx,int yy){ x=xx; y=yy; } }
public class A{ privat int i=0; public class B{ private a=5; } }
public interface Instrument{ public void setPower(boolean power); } public class TV implements Instrument{ // ... public void setPower(boolean on){ if(on){ chargeCondensators(); initTube(); }else{ cutPower(); } } // .. } public class HairDryer implements Instrument{ // ... public void setPower(boolean on){ if(on){ startResistence(); blowAir(); }else{ cutPower(); } } // .. }TV ile HairDryer class'larında setPower method aynı yapıda olmasına rağmen çağrıldığı durumda farklı bir şekilde çalışmakta ve farklı bir işlev göremektedir. Bu nedenle setPower bir polymorphism örneğidir. Aşağıda nasıl kullanılacağı gösterilmiştir.
booelan on=true; booelan off=false; TV tv=new TV(); tv.setPower(on); HairDryer dryer=new HairDrayer(); dryer.setPower(on); tv.setPower(off); dryer.setPower(off);