কম্পিউটার টিউটোরিয়াল

জাভাতে স্ট্যাটিক মেথড ওভারলোড বা ওভাররাইড করা যায় কিনা?


জাভাতে স্ট্যাটিক মেথড ওভারলোড করা যায়। কিন্তু একটি শর্ত রয়েছে যে দুটি মেথড ওভারলোড করা যাবে না যদি সেগুলো শুধু 'static' কীওয়ার্ডের কারণে ভিন্ন হয়।

একটি উদাহরণ দেখা যাক:

উদাহরণ

public class Demo{    public static void test(){       System.out.println("Demo class test function has been called");    }    public static void test(int val){       System.out.println("Demo class test function with parameter has been called");    }    public static void main(String args[]){       System.out.println("In the main class, Demo functions being called");       Demo.test();       Demo.test(57);    } }

আউটপুট

In the main class, Demo functions being called Demo class test function has been called Demo class test function with parameter has been called

Demo নামক একটি ক্লাসে 'test' নামক একটি ফাংশন থাকে যা একটি নির্দিষ্ট মেসেজ প্রিন্ট করে। এটিও 'test' নামক আরেকটি ফাংশন সংজ্ঞায়িত করে যা একটি ইন্টিজার মান প্যারামিটার হিসেবে নেয়। ফাংশন বডির ভেতরে প্রাসঙ্গিক মেসেজ দেখানো হয়েছে। main ফাংশনে test ফাংশন প্যারামিটার ছাড়া এবং একটি ইন্টিজার প্যারামিটার দিয়ে কল করা হয়েছে। প্রাসঙ্গিক মেসেজ কনসোলে দেখানো হয়েছে।

জাভাতে স্ট্যাটিক মেথড ওভাররাইড করা যাবে না। একই সিগনেচার বিশিষ্ট স্ট্যাটিক মেথড সাব-ক্লাসে ডিফাইন করা যাবে, কিন্তু সেটি রানটাইম পলিমরফিজম হবে না। তাই ওভাররাইডিং সম্ভব নয়। একটি উদাহরণ:

উদাহরণ

class base_class{    public static void show(){       System.out.println("Static or class method from the base class");    }    public void print_it(){       System.out.println("Non-static or an instance method from the base class");    } } class derived_class extends base_class{    public static void show(){       System.out.println("Static or class method from the derived class");    }    public void print_it(){       System.out.println("Non-static or an instance method from the derived class");    } } public class Demo{    public static void main(String args[]){       base_class my_instance = new derived_class();       System.out.println("Base class instance created.");       my_instance.show();       System.out.println("Function show called");       my_instance.print_it();       System.out.println("Function print_it called");    } }

আউটপুট

Base class instance created. Static or class method from the base class Function show called Non-static or an instance method from the derived class Function print_it called

বেস ক্লাসে 'show' নামক একটি স্ট্যাটিক ফাংশন থাকে যা একটি মেসেজ প্রিন্ট করে। একইভাবে 'print_it' নামক আরেকটি ফাংশন একটি মেসেজ দেখায়। একটি ক্লাস বেস ক্লাস থেকে ডেরাইভ করা হয়েছে যা দুটি ফাংশন ইনহেরিট করে। Demo নামক একটি ক্লাসে main ফাংশন থাকে যা বেস ক্লাসের একটি ইনস্ট্যান্স তৈরি করে যা ডেরাইভড টাইপ ক্লাসের। প্রাসঙ্গিক মেসেজ কনসোলে দেখানো হয়েছে।


  1. জাভাতে Enum কি কোনো ক্লাস এক্সটেন্ড করতে পারে?

  2. জাভাতে কি প্রোটেক্টেড মেথড ওভাররাইড করা যায়

  3. জাভাতে JTextField-এ প্যাডিং যোগ করুন

  4. জাভা ৮-এ ইন্টারফেসে স্ট্যাটিক মেথড