Can we Override Private Method in Java? Inner Class?

No, you cannot override private methods in Java, private methods are non virtual in Java and access differently than non-private one. Since method overriding can only be done on derived class and private methods are not accessible in subclass, you just can not override them. By the way, one more possibility of overriding private methods in inner class, since private methods are accessible in inner class, and that’s why it is one of the tricky java interview question. Anyway this will also not work because private methods are bonded during compile time and only Type (or Class) is used to locate a private method. For Example in below code where it looks like that nested class is overriding private method, but if you call privateMethod() with a type of super class but object of sub class, it will only execute privateMethod() declared in parent class, which is not exactly method overriding. Had private method overridden that it would have called method from child class. By the way, compiler will not complain, it will treat method with exact same signature in child class as separate method, and this is known as method hiding in Java.


Should I also make private method as final in Java

Can private method be overridden in Java
This is another common doubt among Java programmers, using final and private method in Java is a good choice, but I don't think it offer any benefit in terms of performance. Rather, this decision should be taken on the basis of design, functionality and ensuring readability of code. Since making a method final, just limit it’s ability to be overridden, it doesn't make much sense to mark a private method as final in Java, because private method can not overridden in Java by any means. So compiler will definitely perform sort of optimization it can e.g. inlining or caching it. By the way, private keyword is one of the fundamental access modifier and can be applied to variables, methods and class, let’s see some of the worth knowing fact about private keyword in Java.



Important Points about private keyword in Java

1. You can apply private access modifier fields, methods and any inner class in Java. It’s most restricted access modifier and only accessible in the class they are declared. They are not visible outside the class and accessing them outside will result in compile time error.

2.Top level Classes can not be private in Java. They can only be either public or without any access modifier i.e. only accessible in the package they are declared. In case of public class, name of Java source file must match with the name of public class.

3.Though private methods or variables are not accessible outside of the class, they are declare. They can be accessed via reflection by using setAccessible(true) and changing there private visibility. See this article for more details.

4.As we have seen in this article, private methods can not be overridden in Java, not even inside nested or inner classes.

5.Private members runs faster than non-private one, because of static binding. They are also better candidate for optimization from compiler because they can not be overridden.


Private Method Overriding Example

In order to prove theory, we must see an example. In this Java program, we have declared a private method and trying to override them inside an Inner class. In main method, we are calling private method by using reference variable of Outer class, which is also parent but pointing to object of sub class. Though it does show that private method is accessible in Inner class, you just can not override them. Let’s see what does output shows.

/**  * Java Program to demonstrate, private method can not be overridden in Java,   * not even on Inner classes. Main reason of that behavior is because they are bonded   * using static binding in Java.  */ public class PrivateMemberExample {    private String i_m_private = "I am private member, not accessible outside this Class";    private void privateMethod() {        System.out.println("Private method of Outer Class");    }    public static void main(String args[]) {        PrivateMemberExample outerClass = new PrivateMemberExample();        NestedClass nc = outerClass.new NestedClass();        nc.showPrivate(); //shows that private method are accessible in inner class.               outerClass = nc;        outerClass.privateMethod(); // This will not call private method from inner class,                                    // which shows you can not override                                     // private method inside inner class.     }    class NestedClass extends PrivateMemberExample {        public void showPrivate() {            System.out.println("Accessing Private members of Outer class: " + i_m_private);            privateMethod();        }              /*        * private method trying to be overridden,         * instead it’s just hiding parent class method.        */        private void privateMethod() {             System.out.println("Private method of Nested Class");         }    }}OutputAccessing Private members of Outer class: I am private member, not accessible outside this ClassPrivate method of Outer ClassPrivate method of Outer Class
From output it’s clear that both the call to private method, which is made by using reference variable with type of parent class result in invoking private method from parent class, which is also outer class in our case. Had it was overridden, in case of second call, which is made using object of Inner sub class, would result in execution of private method of nested class. This proves that private method can not be overridden in Java, not in sub class and not even in Inner class.

That's all about question, Can we override private method in Java?. We have learned that this is not possible in Java. Though this is a real tough Java question, especially followup question which involves , Can we override private method on Inner class in Java. It can confuse you, if you are not sure about how private methods are bonded in Java. Let me know, if you think otherwise.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
To implement a custom Adapter in RecyclerView, you need to follow these steps: 1. Create a new class that extends RecyclerView.Adapter. This class will act as the adapter for your RecyclerView. 2. Override the onCreateViewHolder method, which is responsible for creating the ViewHolder objects for each item in the RecyclerView. In this method, you need to inflate the layout for the item and create a new ViewHolder object that holds a reference to the views in the layout. 3. Override the onBindViewHolder method, which is responsible for binding the data to the views in the ViewHolder object. In this method, you need to get the data for the current item and set it to the views in the ViewHolder object. 4. Override the getItemCount method, which returns the total number of items in the RecyclerView. Here's an example code snippet for implementing a custom Adapter in RecyclerView: ``` public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private List<String> mData; public MyAdapter(List<String> data) { mData = data; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.my_item_layout, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { String item = mData.get(position); holder.mTextView.setText(item); } @Override public int getItemCount() { return mData.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { public TextView mTextView; public ViewHolder(View itemView) { super(itemView); mTextView = itemView.findViewById(R.id.text_view); } } } ``` In this example, the MyAdapter class extends RecyclerView.Adapter and takes a list of strings as data in its constructor. The onCreateViewHolder method inflates the layout for each item from a layout resource file and creates a new ViewHolder object. The onBindViewHolder method sets the text for each item in the RecyclerView. Finally, the getItemCount method returns the total number of items in the RecyclerView. Note that in this example, the ViewHolder class is defined as a static inner class of the MyAdapter class. This is a common practice to keep the code organized and to avoid memory leaks.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值