This question already has answers here:
private method in inheritance in Java
(6 answers)
Closed 4 years ago.
// file name: Main.java
class Base {
private void foo() {
System.out.printf("Message");
}
}
class Derived extends Base {
public void foo() {
System.out.printf("Message1");
} // works fine
}
public class Main {
public static void main(String args[]) {
Base d = new Derived();
d.foo();
}
}
when I write Derived d=new Derived() it works fine but when i write Base d =new Derived() it gives error of private function cannot be overrided.
I don't know why you say "It gives error of private fn cannot be overrided" - that's not the error you get when you try to compile this. It gives the following error instead:
$ javac Main.java
Main.java:16: error: foo() has private access in Base
d.foo();
^
1 error
Why: Because foo() is a private method in class Base, so you cannot call it on a variable of type Base.
Also: You can indeed not override private methods; in fact, the foo() method in class Derived is a method that is completely separate from the foo() method in class Base, that just happens to have the same name. It does not override the method in class Base.
This is because foo is private in Base class. You can use public or protected
The method you want to inherit is private. So you don't override it. You hide it instead. So Base.foo and Derived.foo are completely different methods.
Note: hiding private methods is valid
I would suggest you to use #Override annotation on methods you override. It will prevent you from hiding private methods.
Related
This question already has answers here:
Why java.lang.Object can not be cloned?
(10 answers)
Closed 4 months ago.
Object's clone method is protected, therefore it can be accessed in sub classes (class A), so why am I getting 'clone() has protected access in java.lang.Object' compiler error? I thought, that all Java classes are sub classes of Object. Thanks in advance.
The code below raises the compiler error:
public class A {
public static void main(String[] args) {
Object o = new Object();
o.clone();//error
}
}
But this one compiles perfectly, don't they have the same semantics tho?
public class A {
protected void foo() {
}
}
public class B extends A {
public static void main(String[] args) {
A a = new A();
a.foo();
}
}
No, they don't.
protected means 2 things:
It's like package, _and that explains why your second snippet can call foo(). It's not about the fact that B extends A, it's that A is in the same package as B.
Subclasses can invoke it.. on themselves only. Trivially (but this doesn't work if its final), you can simply override it, implement it as return super.clone(); and now you can call it just fine.
protected members can be accessed anywhere in the same package and outside package only in its child class and using the child class reference variable only, not on the reference variable of the parent class. We cant access protected members using the parent class reference.
This question already has answers here:
“overriding” private methods with upcasting call in java
(1 answer)
Overriding private methods in Java
(10 answers)
Closed 5 years ago.
Can anybody explain why output to below question is "A.test" ?
class A {
private void test(){
System.out.println("A.test");
}
public void mytest(){
this.test();
}
}
class B extends A{
protected void test(){
System.out.println("B.test");
}
}
public class Test{
public static void main(String[] args) {
A a = new B();
a.mytest();
}
}
The test() method of class A cannot be overridden by class B, since it is private. Therefore this.test(); invokes A's test() method even though it is executed on an instance of class B.
Super class can invoke the methods of the sub class without using typecasting, without using reflection and without using a reference other than this only if they are overridden.
In your case A a = new B(); , object of B is created which has both the behaviours private void test() as inherited by super class A as well as protected void test() as added by B. The reason for both the methods being there and not just one is that due to the acess modifier being private the method is not visible in subclass scope. Hence it can not overriden and adding the method with same name just simply adds another method.
As there is no run time polymorphism in this case hence compile time target method is resolved and method defined in A is invoked.
If in case you would have overriden the mytest in B and from the overriden mytest you would have made a call to test then method in B would have been invoked. This is easy to understand as any method of B can not see any private method of its super class.
This question already has answers here:
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 7 years ago.
I have a class in a different package where i declared a protected member. as shown
package Pack1;
public class Box {
public Box()
{
System.out.println("Box Class Contructor");
}
protected int x = 1;
protected void Hello1()
{
System.out.println("Hello!!");
}
}
Now i am extending this class to another package to call its protected member as shown:
public class Main extends Pack1.Box {
public Main()
{
System.out.println("main constructor");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Main main = new Main();
main.Hello1(); // not giving me any error
Pack1.Box b = new Pack1.Box();
b.Hello1();//Giving me an error
}
}
I am not sure why b.Hello1() is giving me an error inspite of being inherited. But if i declare the Hello1() as protected static void it is not giving me an error.
For accessing protected method() , variables from class located in other package we need Inheritance.
As i can see you have already used inheritance and inherited the class box of package pack1 correctly.
Now all except default and private members of that class aren't visible. What is visible to you the members those are declared as protected and public.
Now you can assume those methods are available in ur class.
So, instead of calling method by object reference of that class will give you an error , while it won't give you any error if you call that method directly but in the constructor of a class ie Main() class in your case.
Why because,
There are two main restrictions for the static method.
They are:
1)The static method can not use non static data member or call non-static method directly.
2)this and super cannot be used in static context.
Try to call Hello1() method from class constructor. It will work.
The protected method Hello1() is defined in the Pack1, so you can't invoke it from another package - only from subclasses like this:
Main main = new Main();
main.Hello1();
protected allows access from subclasses and from other classes in the same package.
When you use your method static.
You might wonder "what's the reason for a static protected method, considering that it's impossible to call it from anywhere except from an instance of that class?". Usually there isn't much reason to declare a private or protected method as static. Static methods are usually public.
This question already has answers here:
Calling super super class method
(12 answers)
Closed 8 years ago.
Let say I have three classes:
class A
{
public void method()
{ /* Code specific to A */ }
}
class B extends A
{
#Override
public void method()
{
/*Code specific to B*/
super.method();
}
}
class C extends B
{
#Override
public void method()
{ /* I want to use the code specific to A without using B */ }
}
The goal in this case is to use the code from A without using the code from B. I thought there was a way to do it by calling the super method, but this brings in the code from B as well.
Is there a way to do this?
The short answer is no. What you're seeing is that your design is flawed. It indicates that you need too move the code in class A out into a helper class. B and C would then use it via composition. You could try using partials to get the behavior you want. See this link for more details. Partial function application in Java 8
You could instantiate an object of class A in C and call the method method
class C extends B
{
#Override
public void method()
{ /* I want to use the code specific to A without using B */
A test = new A();
test.method();
}
}
Not sure if this is what you meant. Also asumed you forget the method name method in class A.
No there is no way to do it. You can simply create another method in class B that executes the code of A's method, and call that method in subclass C.
Given this code snippet, could you explain why it woks?
The thing is that the class constructor is marked private, so should not it prevent us to call it with new operator?
public class Alpha {
protected Alpha() {}
}
class SubAlpha extends Alpha {
private SubAlpha() {System.out.println("ok");}
public static void main(String args[]) {
new SubAlpha();
}
}
It all works because the static method is part of the class and it can see all private fields and methods, right? Outside this "new" initialization would never work?
The only private constructor in your question is SubAlpha, which SubAlpha itself is calling. There's no issue, a class can call its own private methods. The Alpha constructor is protected, so SubAlpha has access to it.
Edit: Re your edit: Yes, exactly. A separate class (whether a subclass or not) would not have access to SubAlpha's private constructor and could not successfully construct a new SubAlpha().
Example 1:
public class Beta
{
public static final void main(String[] args)
{
new SubAlpha();
// ^--- Fails with a "SubAlpha() has private access in SubAlpha"
// compilation error
}
}
Example 2:
public class SubSubAlpha extends SubAlpha
{
private subsubAlpha()
{
// ^== Fails with a "SubAlpha() has private access in SubAlpha"
// compilation error because of the implicit call to super()
}
}
This is, of course, constructor-specific, since scope is always member-specific. If a class has a different constructor with a different signature and a less restrictive scope, then a class using it (including a subclass) can use that other constructor signature. (In the case of a subclass, that would require an explicit call to super(args);.)
The code works as the main method is also in the same class. You may not be able to initialize SubAplha from a different class.