Override method in inheritance - java

My code:
public class PrivateOverride {
private void f() {
System.out.println("private f()");
}
public static void main(String[] args) {
PrivateOverride po = new derived();
po.f();
}
}
class derived extends PrivateOverride {
public void f() {
System.out.println("public f()");
}
}
Output:
private f()
Why?

Because derived#f() does not override parent's class private f() method.
You could confirm it by adding #Override annotation to f() method in derived class and see that it won't compile.
Extra tips :
To override method f(), it should be inherited from parent's class, i.e. visible in your subclass, which is never the case for private methods.
Additional rules for correct method overriding are summarized in this table.

derived cannot see PrivateOverride's f() because it's private, and hence that is not an overriding, it's definition of a new method. It's always recommended to add the annotation #Override on the overridden method just to avoid such hidden problems.

Method f in PrivateOverride is declared as private. That means that it isn't overridden in derived class.
That's why you should use #Override annotation. In that case it would show you the error.

Because Private method can't be Inherited in subclass so it can't be overridden.

Related

Can I access my protected method from a sub-class by using super keyword I need an explaination

A.java
class A {
protected void msg(){
System.out.println("-------------------asdfghjkl");
}
}
B.java
class B extends A {
public static void main(String args[]) {
B obj = new B();
obj.msg();
}
void dis() {
super.msg();
}
}
Yes, you can.
Explanation: That's according to Language specification. if you want to access a method of base class in derived class, mark that method as protected then using super is optional.
A subclass can access the non-private members of its superclass as if they belong to the subclass itself. You do not need to use super in your example.
Super is aptly used in case of constructor calls, method overriding or in case where subclass hides any superclass member.

Inheritance: weaker accessibility of a method in subclass

what is the need of having a rule like this in java :
"a subclass cannot weaken the accessibility of a method defined in the superclass"
If you have a class with a public method
public class Foo {
public void method() {}
}
This method is accessible and you can therefore do
Foo foo = new Foo();
foo.method();
If you add a subclass
public class Bar extends Foo {
#Override
public /* private */ void method() {}
}
If it was private, you should not be able to do
Foo bar = new Bar();
bar.method();
In this example, a Bar is a Foo, so it must be able to replace a Foo wherever one is expected.
In order to satisfy the above statement, a sub class cannot make an inheritable member less accessible. It can however make it more accessible. (This basically only applies to methods.)
What it means
The subclass method cannot have a more restrictive visibity than the superclass method.
For example, if the superclass defined
protected void a() { } // visible to package and subclasses
the subclass can override it with one of
public void a() { } // visible to all
protected void a() { } // visible to package and subclasses
but not
void a() { } // visible to package
private void a() { } // visible to itself
Why it is
Suppose the definition was
class A {
public void a() { }
}
class B extends A {
private void a() { }
}
Now, consider the following code
A instance = new B();
instance.a(); // what does this call?
On the one hand, any B has a publically accessible a method. On the other hand, the a method of a B instance is only accessible to B.
More generally, a subclass(interface) must fulfill the contract of its superclass(interface).
Visibility is only one example of this principle. Another example is that a non-abstract class must implement all methods of any interface it implements.
class Person {
public String name() {
return "rambo";
}
}
// subclass reduces visibility to private
class AnonymousPerson {
private String name() {
return "anonymous";
}
}
It's legal to call the following method with either a Person, or an AnonymousPerson as the argument. But, if the method visibility was restricted, it wouldnt' be able to call the name() method.
class Tester {
static void printPersonName(Person p) {
System.out.println(p.name());
}
}
//ok
Tester.printPersonName(new Person());
this call is legal, because a Person is a AnonymousPerson, but it would have to fail inside the method body. This violates "type safety".
Tester.printPersonName(new AnonymousPerson());
To fulfill the interface contract. Let's say I have an interface, IFlying, as:
public interface IFlying {
public void fly();
}
And I have an implementation that weakens accessibility:
public class Bird implements IFlying {
private void fly(){
System.out.println("flap flap");
}
}
I now have some library function that accepts an IFlying, and calls fly upon it. The implementation is private. What happens now? Of course, it means that the fly method cannot be accessed.
Hence, the accessibility may not be made more restrictive in an implementation.

Which method is overridden? [duplicate]

This question already has answers here:
Interface and Abstract class ad method overriding
(3 answers)
Closed 8 years ago.
Class A has run() method and interface B also has run() method. Question is simple, which run() method is overridden in Main class and how will we prove this? Why there is no conflict (Compile-time error) in this code?
class A{
void run(){System.out.println("A class");}
}
interface B{
void run();
}
class Main extends A implements B{
public static void main(String args[]){
Main m = new Main();
m.run();
}
// Overridding method
public void run(){
System.out.println("run method");
}
}
run of A is overridden, run of B is implemented. As B is an interface, it only states how your objects behave to others and don't enforce any behavior itself.
run() Method of Interface B will be Implemented in class Main by
overridden method of Class A.
Adding an extra point,
It you will not write the run() method in child class Main, You will not get well known "Unimplemented methods" error. This is true for public methods of class A for non public methods you will get compiler error : The inherited method can not hide public abstract method.
That is because methods of interface are public by default and you can not hide it with default (package private) access modifier.
Sample :
class A{
public void run() {
System.out.println("This method will be inherited.");
}
}
interface B{
void run();
}
class Main extends A implements B{
public static void main(String args[]){
Main m = new Main();
m.run();
}
}
OUTPUT : This method will be inherited.
In above code instance, the run() method is inherited from class A that will implement run() method of interface B.
What will be called is
public void run(){
System.out.println("run method");
}
Why?
You're implementing run of interface B and you're also overriding the A implementation of it.
If you remove the last run() implementation and remove implements B, run() of A will be called.
Interface B says that any class implementing it must have a run method. Main extends A and inherits A's run() method.
Main meets the requirement of the B interface for having a run method. The run method in Main then overrides the run() method it got from the A class.
// This is a class with a run method.
class A{
void run(){System.out.println("A class");}
}
// Anything implementing this interface must have a run method.
interface B{
void run();
}
// This class is an extension of A (and therefore has A's run() method)
// This class implements B and must have a run method, which it does, because it has A's
class Main extends A implements B{
public static void main(String args[]){
Main m = new Main();
m.run();
}
// This method then overrides the run Method it inherited from A
// And this method meets the requirement set by implementing B.
public void run(){
System.out.println("run method");
}
}
There is no conflict because both methods have the same signature. Method declarations in interfaces are not overridden because they don't implement anything. So in this case, run method in class A is overridden.
On the other hand, when overriding methods you are encouraged to use the #Override annotation, e.g.
#Override
public void run() {
....
}
Super class's method is always called as overridden method whereas subclass method is called as overriding method.
Final method cannot be overridden. [if superclass's method is final]
Final methods can override. [Read it as grammatical way. This method is in subclass and is final, but superclass's method is not final]

Java execution flow?

what will be the flow of execution in case of override? What i believe is , when we call a constructor/object of any class, during execution first it call parent constructor and than child. but what will happen in case of over ridding?
lets suppose:
class A {
public A(){
printStatus();
}
public void printStatus(){
System.out.println("In Class A");
}
}
class B extends A{
public B(){
printStatus();
}
#Override
public void printStatus(){
System.out.println("In Class b");
}
}
public class Test2 {
public static void main(String[] args){
B b = new B();
}
}
Out put of this code is:
In Class b
In Class b
what i don't understand is, why it's printing "In Class be" only, it should be "In class A and, In Class b",
when i remove override method from class b. it give me desired output.
All java methods are virtual. It means the method is called with using actual type of this. So inside of constructor A() {} this is the instance of B, so that is why you've got its method call.
Calling like this printStatus() will call the method from the same class. If you call with super.printStatus() it will envoke method from the super class (class which you have extended).
When you over-ride a method you over-ride it completely. The existence of the original implementation is completely invisible to other classes (except via reflection but that's a big topic of its own and not really relevant). Only your own class can access the original method and that is by calling super.methodName().
Note that your class can call super.methodName() anywhere, not just in the overriding function, although the most usual use for it is in the overriding function if you want the super implementation to run as well as your own.
Constructors are a slightly special case as there are rules about how and why constructors are called in order to make sure that your super-class is fully initialized when you try and use it in the inheriting class.
super is always called whether you write super(); or not.
In the example printStatus() method of Class A will never be called. Since you are creating an instance of class B and there will be method overriding. You can use the following to call the Class A printStatus() method.
public B()
{
super.printStatus();
}
When you override a method, it will override the one that you expect from class A.
Should use super keyword for calling super class method.
class A {
public A(){
printStatus();
}
public void printStatus(){
System.out.println("In Class A");
}
}
class B extends A{
public B(){
super.printStatus();
}
#Override
public void printStatus(){
System.out.println("In Class b");
}
}
Constructor public B(){ super.printStatus(); } calls Class A print method and constructor public A(){ printStatus(); } calls Class B print method since you've overridden.
But its wrong with overridable method calls in constructors.
Try with like this :
class A {
public A(){
printStatus();
}
public void printStatus(){
System.out.println("In Class A");
}
}
class B extends A{
public B(){
super.printStatus();
printStatus();
}
#Override
public void printStatus(){
System.out.println("In Class b");
}
}
public class Test2 {
public static void main(String[] args){
B b = new B();
}
}
For better understanding the concepts of Overloading and Overriding just go through this links:
http://en.wikibooks.org/wiki/Java_Programming/Overloading_Methods_and_Constructors

Overriding Protected Methods

I'm new to Java and I have a very basic question.
I have 2 Parent Class under the same package. Animal Abstract Class and the Machine Class.
Now, the Animal Abstract Class has a protected method. I'm aware that protected methods are accessible if the classes are under the same package.
I can access that protected method in my Machine Class, and the question is.. Is it possible to override that protected method? Without extending the Animal Class.
protected - Can be overridden by subclasses, whether they are in the same package or not
default (no access modifier) - can only be accessed or overridden if both the classes are in the same package
You can only override methods through extension.
You can override a protected method with an anonymous subclass, if you like. E.g.
public class Animal {
protected String getSound() {
return "(Silence)";
}
public void speak() {
System.out.println(getSound());
}
}
In another class:
public static void main(String ... args) {
Animal dog = new Animal() {
#Override
protected String getSound() {
return "Woof!";
}
}
dog.speak();
}
Will output:
Woof!
No , Overriding means inherit the behavior from parent class and that is not possible without extending the class.
public class PClass
{
protected boolean methodA()
{
return true;
}
}
public class CClass extends PClass
{
protected boolean methodA()
{
return false;
}
}
Run the code below to test it
public static void main(String[] args)
{
PClass pc = new CClass();
System.out.println(pc.methodA());
}
O/p=false
here we are overriding the behavior of methodA
In order to override a method you have to extend that class. That's what overriding means: having a method with the same signature as the super-class.
Overriding by definition says..
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.
So AFAIK if you don't extend the super class there is no way to override the method.

Categories