Pushpak Kumar
Pushpak Kumar

Reputation: 23

inheritance and protected class java

error: mul(int,int) has protected access in Multiplication

Thoughts on what I'm doing wrong?

public class Multiplication{
            protected int mul(int a,int b){
                return (a*b);
            }
        }

        class ImplimentPkg extends Multiplication {
            public static void main(String args[]){

                Multiplication obj=new ImplimentPkg();
               //Here's the error
                System.out.println(obj.mul(2,4));

            }
            protected int mul(int a,int b){

                    System.out.println("");
                    return 0;
                }
        }

Upvotes: 0

Views: 574

Answers (2)

Sifeng
Sifeng

Reputation: 719

Java tutorial says:

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

You may think you have matched the second case(inheritence).

Multiplication obj = new ImplimentPkg();
System.out.println(obj.mul(2, 4));

This means you are using an instance of parent class Multiplication. Although the code is inside a method of subclass of Multiplication. It doesn't mean the instance obj has something to do with inheritance. And of course the mul(...) method is invisible. What you can do is: use keyword super.

public void bar() {
    Multiplication mul = new Multiplication();
    mul.mul(1, 2);  // <- error
    super.mul(1, 2); // correct
    Multiplication.foo(); // correct
}

Note: if you have protected static method in parent class, like:

public class Multiplication {
    private String name = "some";

    protected int mul(int a, int b) {
        return (a * b);
    }

    protected static void foo() {
        System.out.println("foo");
    }
}

Here the foo() method can be accessed everywhere in subclass, but not other classes. By the way, you shouldn't use protected static method, see reasons here.

Another related topic may be interested to you, see here.

Upvotes: 2

Leonardo Kenji Shikida
Leonardo Kenji Shikida

Reputation: 761

Create each class in its own Java file

ImplimentPkg.java

package my;

class ImplimentPkg extends Multiplication {
    public static void main(String args[]) {

        Multiplication obj = new ImplimentPkg();
        System.out.println(obj.mul(2, 4));

    }

    protected int mul(int a, int b) {

        System.out.println("");
        return 0;
    }
}

Multiplication.java

package my;

public class Multiplication {
    protected int mul(int a, int b) {
        return (a * b);
    }
}

Upvotes: -1

Related Questions