Introduction
Encapsulation is one of the basic concept of OOP (object-oriented programming) that is not only applicable to a object but as well as to a method or code block (Language dependence)
‘Encapsulating’/Inlining a method can be useful as it make code easier to read and maintain, especially if the enclosing method is only called once or infrequently. If a method is frequently called, it will be more efficient to make the code a method of persistent class to prevent unnecessary instantiation of class/object.
The following example show the realistic use of inline method when setting similar property of a group of JButton component. And so I will use the example to demonstrate way of inlining method. The following example requires Java 1.5/1.6 to run.
Code
copy from here ===================================
import javax.swing.*;
import java.awt.*;
class TestMethod
{
private JButton but1 = new JButton(”but2″),
but2 = new JButton(”but2″);
// #1: Inline Method using inner class ===========
private void method1()
{
class ConfigureCmp
{
Dimension dim = new Dimension(30, 30);
void setup(JButton button)
{
button.setSize(dim);
}
}
ConfigureCmp t = new ConfigureCmp();
t.setup(but1);
t.setup(but2);
}
// #2: Inline Method using Generics and Variable argument. ===========
private void method2()
{
Utility.implement(new Utility.IImplementation()
{
Dimension dim = new Dimension(30, 30);
public void setup(JButton _but)
{
_but.setSize(dim);
}
},
but1, but2);
}
public static void main(String[] _args)
{
TestMethod testMethod = new TestMethod();
testMethod.method1();
testMethod.method2();
System.out.println(”Done…”);
}
}
final class Utility
{
public static interface IImplementation
{
void setup(D _obj);
}
public static void implement(IImplementation impl, D… arrayObj)
{
for (D i : arrayObj)
{
impl.setup(i);
}
}
}
End here ===================================
Conclusion
The first way actually instantiate a class within a method so that setup can be called on several JButton objects. However, user must instantiate class and assigned to a reference to call the setup method. No static method is allowed as it is a inner class. The user must also explicitly execute the setup method for each JButton.
The second way takes advantage of the power of Generics and Variable Argument feature of Java 1.5 Onwards. The code look more elegant and user does not need to call setup for each JButton, but rather add the JButton as additional variable argument. The Utility class can be reused for general purpose.
Although both implementations are workable, it is just a better of preference. For I prefer to use method2 in my quest for writing ‘beautiful and elegant‘ code.



hlujgixcczyojegxwell, hi admin adn people nice forum indeed. how’s life? hope it’s introduce branch