Which Method will get override from interface or class? - java

In the below program I had extended Demo1 class and implemented Demo interface and in Practice class I override public void demo() which was declared in both class and interface then from which that method will get Override? and why?
interface Demo{
void demo();
}
class Demo1{
int i=10;
public void demo() {
System.out.println("this is demo"+i);
}
}
public class practice extends Demo1 implements Demo {
public static void Main(String[] args ) {
practice p=new practice();
p.demo();
}
public void demo() {
System.out.println("This is Overrided method");
}
}

The short answer is that it doesn't matter. What the compiler is is looking for is that the signature of the abstract interface method is implemented in your class, or inherited from a supertype (and it doesn't care whether that inherited signature was meant to implement the abstract method in question). And whether your demo() method is called on a practice object declared as Demo or Demo1 is also irrelevant the method signature is implemented either way.
You can, in fact, even remove your demo() override (assuming you didn't need to change the behavior), and the code would still compile:
class practice extends Demo1 implements Demo {
public static void Main(String[] args) {
practice p = new practice();
p.demo();
}
}
That is, even if Demo1.demo() has nothing to do with Demo.demo(), the fact that practice inherits Demo1.demo() which has the same signature as Demo.demo() and without violating access and exception constraints, that makes practice a valid implementation of Demo.

Method from interface is not overrided, it's implemented.
Your practice class inherits the demo method from Demo1 class and this method will be used to implement Demo interface method if you omit the implementation of demo method in practice class itself.
Since you implement the demo method in practice class itself - this method overrides the method from Demo1 class and also implements the method from Demo interface

If you run the below code
public class practice extends Demo1 implements Demo {
public static void main(String[] args ) {
practice p=new practice();
p.demo();
}
public void demo() {
System.out.println("This is Overrided method");
}
}
Output will be "This is Override method" and if you comment the demo method like below
public class practice extends Demo1 implements Demo {
public static void main(String[] args ) {
practice p=new practice();
p.demo();
}
/*public void demo() {
System.out.println("This is Overrided method");
}*/
}
Output will be "this is demo10". In first case as class object finds definition of demo in self, it will give preference to this over to parent class.

Demo1 is providing implemetation of demo(). so it will take parent demo() method. Output will be
this is demo10
But then you have implemented again overriding of demo() method in child class practice
so output is now
This is Overrided method

Related

method implemented in abstract class, but appears in interface

I'm learning abstract classes vs interfaces at the moment and trying to figure out situations where to use one over the other. I'm having trouble figuring out this example at the moment:
public interface Face {
public void test();
}
public abstract class Tract {
public void test() {
System.out.println("over here");
}
}
public class Thing extends Tract implements Face {
public void test() {
// what should print out?
}
}
Here, the test() function is implemented in the abstract class. If you don't implement it in the subclass, would it call the abstract class' method and print out "over here"? Does the interface accept implementations from an ancestor class or do you have to implement it in the subclass, therefore overriding the abstract class implementation?
All the interface cares about is that the class has implemented a method called test() that returns void. It does not matter whether the method is implemented in the class directly or in any ancestor (parent) class.
In your case, the Thing class has inherited its definition of test() from Tract, and therefore implements the Face interface without you having to provide a definition explicitly.
In the class "Tract" you have given an implementation for the method coming from the interface. Also you override it in "Thing" class so when calling this method on a Thing instance then this version(Thing version) is going to be called.
All java methods are virtual.
lets consider little bit modified code,
I hope, you will get the idea:
public interface Face {
public void test();
}
public abstract class Tract {
public void test() {
System.out.println("Tract here");
}
}
public class Thing extends Tract implements Face {
public void test() {
System.out.println("Thing here");
}
}
public class Thing2 extends Tract implements Face {
}
lets go to output:
Tract tr = new Tract();
tr.test();
will not compile because you can't instantiate abstract class.
Thing th = new Thing();
th.test();
will print "Thing here"
Thing2 th2 = new Thing2();
th2.test();
will print "Tract here",
because you not overwritten the test() method in abstract class.
Main idea of this approach - you can abstract implementation in the future use
class C {
void print(Face face) {
face.test();
}
}
new C(new Thing()).print();
will print "Thing here";
new C(new Thing2()).print();
will print "Tract here";
You can hide different implementations
But this is not main idea of abstract classes.
main idea abstract classes are:
public interface Face {
public void test();
}
public abstract class Abstract {
abstract public void test();
}
public class Thing1 extends Abstract implements Face {
public void test() {
System.out.println("Thing1 here");
}
}
public class Thing2 extends Abstract implements Face {
public void test() {
System.out.println("Thing2 here");
}
}
main idea - you can declare method without implementation
new C(new Thing1()).print();
will print "Thing1 here";
new C(new Thing2()).print();
will print "Thing2 here";
main idea - you declare the method in abstract class, that you MUST override to compile code.
I hope, this is enough explained answer.

Implementing interface to a abstract class Java

I was testing a program in which i was trying to implement a interface on abstract class . as given below
interface Inf{
void display();
}
abstract class InfTst implements Inf{
}
class InterfaceTest extends InfTst{
void display(){
System.out.println("Hello");
}
}
but it is shows error
error: display() in InterfaceTest cannot implement display() in Inf
void display(){
what is this error means and how resolve it, please help me.
When you omit access modifier on an interface it defaults to public, but on concrete classes it defaults to package-private.
Change your method signature to below in concrete class InterfaceTest
public void display(){..}
In concrete classes by default package is private. A concrete method means, the method have complete definition so must be your method modifier are always public.
package domain;
interface Inf {
void display();
}
abstract class InfTst implements Inf {
}
class InterfaceTest extends InfTst {
public void display() {
System.out.println("Hello");
}
}
public class StackOverFlow extends InterfaceTest {
public static void main(String[] args) {
StackOverFlow sof = new StackOverFlow();
sof.display();
}
}
output : - Hello

error on Implement interface in main class

Hi friends im learning java from basics..
I have some doubt in implementing interface.
WORKING CODE
Using interface in a class is working....
interface bala
{
void prnt();
}
class ex implements bala{
#Override
public void prnt() {
System.out.print("hi");
}
}
public class Solution
{
public static void main(String arg[])
{
ex p = new ex();
p.prnt();
}
}
NOT WORKING
Here is my doubt, why i cant implement interface in main method?
plea
interface bala
{
void prnt();
}
public class Solution implements bala
{
public static void main(String arg[])
{
prnt();
}
#Override
public void prnt() {
System.out.println("hi");
}
}
What is happening here?
Why implementing on main() is not working?
Is there is a way to make working interface on main function?
Given Bellow code works well.
interface bala
{
void prnt();
}
public class Solution implements bala
{
public static void main(String arg[])
{
Solution sol = new Solution();
sol.prnt();
}
public void prnt() {
System.out.println("hi");
}
}
It's not working, because you're trying to access non-static (i.e. instance) method from a static context.
In order to invoke it, you need an instance of the Solution class (note that in your working code you have an instance of the ex class, so here you need to do the same with slight difference):
Solution instance = new Solution();
instance.prnt();
Problem is main() is static, static blocks can access static members or with object reference . So here you could simply create an object/instance to invoke the method:
new Solution().prnt();
try new Solution().prnt() instead of calling prnt()
the problem is :
main method is a static method. And your overridden method is non-static. You can't call non-static methods from static context.
In order to call overridden method prnt() to call, you need to instantiate you Solution class like -
Solution sol = new Solution();
and then
sol.prnt();
Best Option to Do it . Create the instance of class and Access it.since main method is a static method you can do like that
Solution instance = new Solution();//Creating instance of class
instance.prnt();//access prnt .
You should create the object of Solution class in main method
Solution s1 = new Solution();
s1.print();
Otherwise, you can create the method as static because you are trying to access
the method from static context.

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]

Can an abstract class have a final method?

Can an abstract class have a final method in Java?
Sure. Take a look at the Template method pattern for an example.
abstract class Game
{
protected int playersCount;
abstract void initializeGame();
abstract void makePlay(int player);
abstract boolean endOfGame();
abstract void printWinner();
/* A template method : */
final void playOneGame(int playersCount) {
this.playersCount = playersCount;
initializeGame();
int j = 0;
while (!endOfGame()) {
makePlay(j);
j = (j + 1) % playersCount;
}
printWinner();
}
}
Classes that extend Game would still need to implement all abstract methods, but they'd be unable to extend playOneGame because it is declared final.
An abstract class can also have methods that are neither abstract nor final, just regular methods. These methods must be implemented in the abstract class, but it's up to the implementer to decide whether extending classes need to override them or not.
Yes, it can. But the final method cannot be abstract itself (other non-final methods in the same class can be).
Yes, there may be "final" methods in "abstract" class.
But, any "abstract" method in the class can't be declared final.
It will give "illegal combination of modifiers: abstract and final" error.
public abstract final void show();
illegal combination of modifiers: abstract and final
Here is the working example of the implementation.
abstract class Sian //ABSTRACT CLASS
{
public final void show() // FINAL METHOD
{
System.out.println("Yes");
}
public void display()
{
System.out.println("Overriding");
}
public abstract void success();
}
class Ideone extends Sian //INHERTING ABSTRACT CLASS
{
public void display()
{
System.out.println("Overridden");
}
public void success() //OVERRIDING THE ABSTRACT METHOD
{
System.out.println("Success overriding");
}
public static void main (String[] args) throws java.lang.Exception
{
Ideone id = new Ideone(); //OBJECT OF SUBCLASS
id.show(); //CALLING FINAL METHOD
id.display(); //OVERRIDDEN METHODS
id.success();
}
}
OUTPUT:-
Yes
Overridden
Success overriding
Here is the ideone link:- http://ideone.com/G1UBR5
Yes.
Hint: just fire up your favorite IDE (eclipse, netbeans, etc) and try it out. It will complain if it does not work.
Yes.
Yes, those methods cannot be overriden in subclasses. An example of that is the template method pattern...
Yes it can ... need more characters
Of course, it means you can subclass it, but you cannot override that particular method.
Yes. The abstract modifier makes it possible to omit some of the implementation of a class (i.e. have some abstract methods) but does not impose any restrictions on you.
In Abstract Class methods may be defined or not. If we extend the abstract class then only it has meaning, so what ever methods we declare or defined in Abstract call it will over ride in subclass. So we can declare a method as final in Abstract class, and it will be over ridden in subclass.
Suppose I want to designed class which has some implementation but I do not want others(sub classes) to implement it but other methods, then in that case we need a final implemented method and obvious choice abstract class.
Yes, We can write the final method with implementation.
public abstract class AbstractWithfinalMethod {
public static final boolean m1() {
System.out.println(" M1 method executed");
return true;
}
public static void main(String[] args) {
System.out.println(m1());
}
}
output:
M1 method executed
true

Categories