How can I override object methods inside interface? - java

All classes in java extend the Object class implicitly. But that doesn't concern interfaces. Interfaces can only extend other interfaces, but no classes. However, I can override object class methods inside my interface.
public interface NewInterface {
#Override
boolean equals(Object var1);
#Override
int hashCode();
}
Can you please explain in simple words how is this even possible? Is there any use case for this?

Interface is a just contract. It says that all classes that inherits interface should implement these methods. Interface cannot have implementation. It is possible to override a class that implements this interface.
However, from Java 8 you can define static methods in interfaces in addition to default methods.
UPDATE:
The members of an interface are:
Those members declared in the interface.
Those members inherited from direct superinterfaces.
If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method corresponding to each public instance method declared in Object, . It is a compile-time error if the interface explicitly declares such a method m in the case where m is declared to be final in Object.
Now it is clear that all superinterface have abstract member method corresponding to each public instance method declared in Object .
Read more about interface members here

Related

Difference in method accessibility of class and interface methods in Java

Why does class ref type and interface ref type have a different access scope of their methods.
In the following example
interface ImInterface{
void do1();
void do2();
}
class MyClass implements ImInterface {
void do1(){
System.out.println("do1");
}
void do2(){
System.out.println("do2");
}
void do3(){
System.out.println("do3");
}
}
Could you help me understand why mc variable defined like
MyClass mc = new MyClass();
cannot access do1 and d2 without any cast? It implements all functionality from contract (ImInterface). Why is it like this in Java?
Also, why mi defined like
MyInterface mi = new MyClass();
cannot access do3 without any cast?
I know both mi and mc have different types, but after implementations both become one now, then why it's a difference to access without cast? mc and mi both point to same type of instance.
Since you are declaring the object mi as of type MyInterface, you will only have access to the methods that are declared on MyInterface.
When you declare the object mc as of type MyClass, you will have access to all the methods declared in MyClass and its superclass.
When Java looks at the reference mi, it will just know that it is of type MyInterface.
Now if you declared mc outside of the package then you won't be able to access any of their methods because they have package visibility.
Why mc cannot access do1 and d2 without any cast ?
It can, provided you call mc.do1() or mc.do2() from a class within the same package where MyClass is declared. In Java, when you don't declare an access modifier for a method or a field, Java allows it to be accessible only within the same 'package' where the class is declared. For do1() and do2() to be accessible anywhere, declare them with a public 'modifier':
public void do1() {
...
}
Note: This is not applicable for interfaces as all methods in interfaces are by default 'public', even when the keyword is not specified.
Why mi cannot access do3 without any cast ?
That's how Java is designed. An interface specifies a contract (what, and not, how). So when a class implements an interface, it has to adhere to that contract, plus it can declare it's own functionalities. But as long as you refer to the object of the implementation class with the reference of the interface:
MyInterface mi = new MyClass();
the interface reference will be able to access only the method it has declared. In other words, the interface reference can only tell what it 'knows for sure' to be present in the implementation (as the implementation class has implemented the interface) and not the other functionalities (methods) of the implementation class.
Methods of an interface are implicitly public and methods of a class with no specified access modifier have weaker access privileges than public.
When you implement an interface's method, the implementing class cannot have weaker access modifier for it than specified in the interface.
In your example you are trying to implement an interface with implicitly public methods through methods that have no modifier, violating the rule above. If you want to make this code work, you should make these methods explicitly public.
mi cannot access do3() because it has no information about this method in ImInterface declaration (and mis type is ImInterface). This is the reason you have to explicitly cast mi to MyClass, telling Java that it can treat this object in by more "narrow" means.
You can find more information about interfaces here.

abstract method in class

A class automatically becomes abstract class when any of its method declared as abstract.
I take this point in some blog. Can someone explain me Why entire class becomes abstract when we use only one abstract method.?
Because it can't be instantiated directly anymore. Also, it's then a compiler error if you don't mark the class itself as abstract.
First of all, I'm going to guess that the blog you mentioned was actually discussing C++. In Java, it's a compiler error to declare an abstract method within a class that is declared with the abstract keyword. With that said, Consider this (erroneous) code:
class A
{
abstract void foo();
}
A a = new A();
a.foo(); //Whoa! what are we supposed to do??!
If A had been declared as abstract (as would be required in real code), it would have been impossible to instantiate it.
If any part of a class is missing (that is, it is declared abstract), the class must be abstract because parts of it cannot be used.
In C++, there is no abstract keyword-- a class is automatically abstract if it has any abstract methods (referred to as pure virtual functions in C++).
In Java on the other hand, a class is only abstract if it is declared with the abstract keyword. However, this keyword is required if there are any abstract methods, so the only difference between the two systems in practice is that Java allows abstract classes to not have any abstract methods. In both languages, a class must be abstract if it has any abstract methods: in C++, this is simply how abstract classes are defined, and in Java it is required via the mechanics of the abstract keyword.
Once a method is abstract, it is declared to have no implementation. How would you suggest the VM instantiate an instance of that class?
An abstract method is one that defines a contract for a method but does not implement the functionality.
To instantiate a class with methods that cannot meet the contract defined as there is no implementation wouldn't work. Thus an abstract method means that you should not be able to instantiate the class.
A class automatically becomes abstract class when any of its method declared as abstract.
Can someone explain me Why entire class becomes abstract when we use
only one abstract method.?
The class has to be declared Abstract because the compiler expects a body for a normal class's method otherwise it will throw error. So either you write the method's body or declare the class Abstract
Example:
class SomeClass{
// Method without body
public void SomeMethod();
public static void main(String[] args) {
}
}
When you try to compile it, you will get:
SomeClass.java:4: missing method body, or declare abstract
public void SomeMethod();

Interfaces and Abstract Classes in Java

Does interfaces and abstract classes in Java extend base Object class? Logical answer which I can think of is no, but if interface does not extend Object class, then can please someone explain me the below code:
interface A {
#Override
public int hashCode();
#Override
public String toString();
}
In above case, A interface is the new interface declared. Yet, no class is implementing it. Then how come the methods from Object class visible in the interface?
If it doesn't extend Object class, then why I can't declare following method in the interface:
public Class getClass();
When I tried to declare this method in the interface, it says that it can't override this method, inherited from Object class, as it is declared as final method in Object class.
Interface could only extend some other interface and no - there is no some root interface. Abstract class, as any other class in Java, has Object as its ancestor - while it may not be a direct parent.
Methods, marked as final, could not be overriden in successor classes. As your class has Object as its ancestor - this rule also applies here.
The reason this is can be found in JLS $9.2
If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.
It is a compile-time error if the interface explicitly declares such a method m in the case where m is declared to be final in Object.
And as seen in Object#getClass:
public final Class<?> getClass()
Interfaces do not inherit from Object, but they do mimick the methods available by implicitly adding them. Likewise here, a final method in that base interface can't be overridden in your self-defined interface.

is abstract a must or not?

As you know, in a java interface, all methods have to be defined as abstract. But when I define a method as not typing abstract, the compiler says it is okay. I know that an abstract method must not have a body. Does a method somewhere in an interface necessarily have a name abstract or not? : What i mean is, what is the difference between:
public interface blabla {
public void aMethod();
//or
public abstract void aMethod();
}
No, marking an interface method as abstract has no meaning and is never required.
All interface methods are implicitly abstract (and public too btw).
From the JLS:
Every method declaration in the body of an interface is implicitly abstract, so its body is always represented by a semicolon, not a block.
Every method declaration in the body of an interface is implicitly public.
For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.
It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.
Related question (+ answer with a historical reference to a statement saying that abstract was once required for interface methods):
Java abstract interface
See the sample example below
interface xyz
{
void methodA();
}
Save this to xyz.java
Now compile this using javac tool
and then use the command given belo
javap xyz
the output would be
Compiled from "xyz.java"
interface xyz {
public abstract void methodA();
}
That means when you compile an interface, compiler makes its signature to public and abstract by default.
So it is not necessary to use abstract keyword for any method of interface.
I don't know that they have to be defined as abstract. Probably because they don't. See Oracle's tutorial.
you don't need to specify abstract (default) because within an interface it does not make sense as all the method of the interface needs to be implemented
All methods in an interface are abstract by definition.
You can't create an object out of an interface (e.g., using Interface i = new Interface();) so there's no difference between marking a method as abstract or not.
Any class that implements the interface needs to decide whether to implement it or to let a subclass do it. So as far as the interface is concerned, all methods are abstract by default.
An abstract method provides no implementation. A class which has an abstract method is necessarily abstract, which means that you cannot create instances of this class. To create an instance of that class, you need to subclass and provide non-abstract overwrites for the abstract methods.
An interface never provides an implementation of its methods and it cannot be instantiated. Therefore every method of an interface is per definition abstract. You do not need to provide the keyword abstract when declaring a method in an interface. And by convention the keyword abstract is not used within an interface.
The methods of an interface don't have to be explicitly defined as abstract because they are implicitly abstract and public as defined in the Java Language Specification ยง9.4. A redundant declaration is perfectly legal though.
If you forgot to put abstract keyword before interface method, Java will implicitly put public abstract keyword before it. Because all interface methods must be abstract.

Different rules for abstract methods in abstract class and interface

We cannot declare abstract methods in interface as protected and default (even if we don't mention any access specifier (default) compiler takes it as public)
but we can declare abstract method in abstract class as protected and default.
Why there are different rules for abstract class and interface?
Because abstract methods of abstract classes are meant to be hooks for subclasses. On the other hand interfaces are not concerned with implementation details - they are only about contracts with the "outside world". And a protected method is an implementation detail.
we cannot declare abstract methods in interface as protected and defaul
the purpose of Interface is to just declare contract. your client will implement it and for that it must be public.
also field in interface are public static final by default,
public you got ,static because it can't be instantiated without implementation and it must not be inherited also.
Update:
as per your question
you want to apply some strict constraint which your implementor can't see ..then what is the use of abstract method in abstract class that must be implemented by any concrete class in the inheritance hierarchy...then no one will be concrete class
public class BaseAbstractClass {
private Connection getConnection(){
//somecode
}
public boolean save(){
//get connection and do something
//return ;
}
//your implementor is left to implement it , he can use save method but can'ge see what it does i mean i doesn't have access to getConnection
public abstract void saveEntity();
}

Categories

Resources