জাভা ৯-এ ইন্টারফেস-এ প্রাইভেট মেথড ফিচার যোগ করা হয়েছে। প্রাইভেট মেথড প্রাইভেট মডিফায়ার ব্যবহার করে ডিফাইন করা হয়। জাভা ৯ থেকে ইন্টারফেসে প্রাইভেট এবং প্রাইভেট স্ট্যাটিক মেথড উভয়ই যোগ করা যায়।
ইন্টারফেসে প্রাইভেট মেথডের নিয়মাবলী:
- একটি প্রাইভেট মেথডের ইন্টারফেসে বডি থাকতে হয় অর্থাৎ আমরা সেটিকে নরমাল অবস্ট্রাক্ট মেথডের মতো ডিক্লেয়ার করতে পারি না। যদি আমরা বডি ছাড়া প্রাইভেট মেথড ডিক্লেয়ার করতে চাই তবে এরর থ্রো করবে: "This method requires a body instead of a semicolon"।
- ইন্টারফেসে প্রাইভেট এবং অবস্ট্রাক্ট মডিফায়ার একসাথে ব্যবহার করা যায় না।
- যদি আমরা ইন্টারফেসে একটি স্ট্যাটিক মেথড থেকে প্রাইভেট মেথড এক্সেস করতে চাই, তবে সেই মেথডটি প্রাইভেট স্ট্যাটিক মেথড হিসেবে ডিক্লেয়ার করতে হবে কারণ নন-স্ট্যাটিক মেথডের স্ট্যাটিক রেফারেন্স তৈরি করা যায় না।
- একটি প্রাইভেট স্ট্যাটিক মেথড নন-স্ট্যাটিক কনটেক্সট থেকে ব্যবহার করা মানে সেটি ইন্টারফেসে একটি ডিফল্ট মেথড- থেকে আহ্বান করা যাবে।
সিনট্যাক্স
interface <interface-name> {
private methodName(parameters) {
// some statements
}
}
উদাহরণ
interface TestInterface {
default void methodOne() {
System.out.println("This is a Default method One...");
printValues(); // calling a private method
}
default void methodTwo() {
System.out.println("This is a Default method Two...");
printValues(); // calling private method...
}
private void printValues() { // private method in an interface
System.out.println("methodOne() called");
System.out.println("methodTwo() called");
}
}
public class PrivateMethodInterfaceTest implements TestInterface {
public static void main(String[] args) {
TestInterface instance = new PrivateMethodInterfaceTest();
instance.methodOne();
instance.methodTwo();
}
}
আউটপুট
This is a Default method One... methodOne() called methodTwo() called This is a Default method Two... methodOne() called methodTwo() called