Friends, I have an issue in Java: I'd like to implement one structure but I'm facing some difficulty in doing it, can anyone help me.
interface samp1{
method1()
method2()
method3()
}
interface samp2{
method4()
method5()
}
class Samp implements samp1,samp2
{
// this class needs only method1 from interface samp1 and method 4 from interface samp2
// I don't want to override all the methods from interface
}
can anyone propose some solutions for this?
Is there any design pattern available for this? If so, please provide links to reference.
Thanks in advance.
An interface is a contract. It says "My class implements all of these methods".
See: http://docs.oracle.com/javase/tutorial/java/concepts/interface.html
If you don't want that, don't use an Interface.
Java 8 allows default methods in an interface, that are used if the particular method is not overridden when the interface is implemented.
For example:
interface MyInterface{
//if a default method is not provided, you have to override it
public int Method1();
public default int Method2(){
return 2;
}
}
public class MyClass{
public static void main(String args[]){
MyInterface in = new MyInterface(){
public int Method1(){
return 0;
}
};
//uses the implemented method
System.out.println(in.Method1()); //prints 0
//uses the default method
System.out.println(in.Method2()); // prints 2
}
}
There is no other way than to implement all the methods in the interface, when you implement the interface. In the above class "samp" you are implementing "samp1" and "samp2" interface's, so you have to implement all the methods in samp1 and samp2 in samp class.
you said override methods from the interface. you don't override methods from interface, you just implement methods.
you can solve your problem by using abstract class.
abstract class AbstractSamp implement samp1,samp2{
method1(){...}
method4(){...}
}
and you can extend Abstractsamp in your samp class as below
class samp extends AbstractSamp{
// here you can extend method1() and method4() by inheritence and you can also override them as you want
}
Declare the class as abstract and you won't need to implement all the methods. However, please note that abstract classes cannot be instantiated.
Without having more context on what you are trying to achieve, this is what I suggest to do:
interface BaseSamp {
void method1();
void method4();
}
interface Samp1 extends BaseSamp {
void method2();
void method3();
}
interface Samp2 extends BaseSamp {
void method5();
}
class YourClass implements BaseSamp {
....
}
interface MySpecializedInterface{
public void method1();
public void method4();
}
class YourClass implements MySpecializedInterface{
// now you can implement method1 and method4... :|
}
Related
I am studying for OCA and I try to find answer for every question I encounter in my head.
This is the code:
interface InterfaceA {
public default Number method(){
return 5;
}
}
abstract class AbstractB {
public Long method() {
return 3L;
}
}
public class Foo extends AbstractB implements InterfaceA {
public static void main(String[] args) {
System.out.println(new Foo().method());
}
}
}
In this situation I don't have to override in the class Foo.
I know if I implement 2 interfaces with same methods I have to explicitly override in the class Foo. In the example above I get the result from AbstractB (3). My question: is abstract class implicitly overriding or hiding the method from the interface? What is the reason that class Foo prints the result from AbstractB and not from InterfaceA?
Abstract classes implement methods from interfaces. This does not count as an override, because there is no base method to override. In other words, if you try to do this
abstract class AbstractB {
public Long method() {
return super.method(); // <<==== Does not compile!
}
}
the call to base class method() would not compile.
Hiding does not apply either, because only static methods in Java can be hidden.
why class Foo gets the result from his parent class and not from interface?
Because interface provides a default implementation, i.e. what you get when there's nothing else provided in the line of inheritance. In this case, abstract base class provides an implementation, so it "wins" over the default implementation from the interface.
in this specific case the call to println prints 3 because AbstractB implements the method method of the interface InterfaceA in which case the class Foo inherits this bevahior. However, had AbstractB not implemented the interface method the println call would delegate to the default method of InterfaceA. Lastly, to answer your question AbstractB does not hide the method of the interface rather implements it as it has the same signature as the method in InterfaceA.
This question was asked to me in an interview. Tired of googling here I am.
I have an interface with 100 methods. I don't want to implement all those 100 methods in a single class. Is there any way I could implement these 100 methods by using more than one class and not repeating the implementation ?
For Example :
Class A implements first 10 methods(only).
Class B implements next 10 methods(only) and so on.
Note :
1. All the classes which implements the interface must be concrete.
As far as my knowledge on java this isn't possible. He mentioned about adapter when he asked me this question. That made me think that there's a way to do it.
Can anybody clarify me on this ?
Write an adapter with empty implementation of the 100 methods
class Adapter{
//write your empty implementations here as similar to KeyListener in Java
// They have written a keyAdapter and make use of key adapter.
}
ie) class Adapter implements interface1{
public void method1(){}
public void method2(){}
.....
}
You can extend the adapter class in some other class and just override the methods.
class A extedns Adapter{
public void method1(){
}
}
ie)
The concept you describe is called partial classes and Java does not have such a concept.
Here is a similar answer: A way to implement partial classes in java
If you use Java 8 , you can define default implementations in the interface for the 100 methods like :
public interface MyInterface{
void methodA();
int methodB();
default boolean methodC(String name) {
return name.equals("Default");
}
}
Then in your concrete classes you only implements the methods you want. All other not overriden methods will use the default implementation from the interface.
You will have to write 100 default implementations in the interface but it will save you the need to also write 100 implementations in every concrete class implementing that interface.
Again, this is only available since Java 8.
Write all the classes (A, B, C, D, E each implement 20 methods) witch extend one another without implementing the interface I:
I
|
A <- B <- C <- D <- E
And only the last one implements the interface.
Simpler exemple with only 2 methods:
public interface I {
void a();
void b();
}
public class A {
public void a() {
}
}
public class B extends A implements I {
public void b() {
}
}
If the interface methods defined with default implementation ;
public interface I {
default void a(){
//implementation
}
default void b(){
//implementation
}
default void c(){
//implementation
}
//97 more
}
public class A implements I{
#override
public void a() {
}
}
public class B extends A {
#override
public void b() {
}
public class C extends B {
#override
public void c() {
}
}
Even without inheritance classes can be independent from each other and they can provide implementation for different methods
You are correct - any concrete class must implement all methods, so the only way you can not do it is either extend the class that implements given interface and override some of the methods in subclass or implement methods calling implementations from other classes
Suppose I have an interface which has 3 methods. This interface is to be implemented by many classes but the implementation of say method1 will be same in all classes.
I can make an abstract class and give a concrete implementation for method1 and let my classes extend this class.
My question is when I am already extending a class, how do I also extend this abstract class. Java doesn't support it. How should I design in such a scenario?
interface Inf{
void method1();
void method2();
void method3();
}
public abstract class Abs implements Inf{
void method1(){
//concrete implementation
}
}
class Test extends SomeClass implements Inf{
//here I need method1 implementation and other methods Ill implement
}
class SomeClass{
}
With java 8, you can define default implementation of a method inside the interface.
public interface A {
default void method1() { System.out.println("Default method1 implementation"); }
void method2();
void method3();
}
Java doesn't support Multiple Inheritance. i.e A Class cannot have more than one Base class. What you can do is make the SomeClass to extend Abs class
class SomeClass extends Abs{
}
class Test extends SomeClass implements Inf{
//here you can get method1 implementation since Someclass extends Abs
}
Note : As said by #anonymous , you can make use of default methods of interface if you work in Java 8
Java doesn't support multiple inheritance.
You can make your Abs class to extend SomeClass
class Abs extends SomeClass {
}
class Test extends Abs implements Inf {
}
I came to situation :
public interface Intr {
public void m1();
}
public abstract class Abs {
public void m1() {
System.out.println("Abs.m1()");
}
// public abstract void m1();
}
public class A extends Abs implements Intr {
#Override
public void m1() {
// which method am I overriding, well it is Abs.m1() but why?
// if method implemented is Abs.m1(), then why I am not getting error for Intr.m1() not implemented.
}
}
You are satisfying both conditions at once; ie. the one implementation is at the same time fulfilling the abstract class requirements and the interface requirements.
As a note, unless you are using Intr in another inheritance chain, you don't need it. Also, it might make sense to move the implements Intr up to the abstract class definition.
You can only override methods defined in another class.
Methods declared in an interface are merely implemented. This distinction exists in Java to tackle the problem of multiple inheritance. A class can only extend one parent class, therefore any calls to super will be resolved without ambiguity. Classes however can implement several interfaces, which can all declare the same method. It's best to think of interfaces as a list of "must have"s: to qualify as a Comparable your cluss must have a compareTo() method but it doesn't matter where it came from or what other interfaces require that same method.
So technically you override Abs.m1() and implement Intr.m1() in one fell swoop.
Note that this would be fine too:
public class B extends Abs implements Intr {
//m1() is inherited from Abs, so there's no need to override it to satisfy the interface
}
Here, both the interface and abstract class have the same method.
You have one class with named Derived which extends an abstract class and implement an interface. It's true and you override print method on Derived class it's fine and it compiles correctly and does not give any error but here you can't identify which class method is overridden like abstract class or interface.
This is runtime polymorphism you can't create an instance of an abstract class or interface but you can create a reference variable of that type. Here the solution is you can't identify that on compile-time it's actually overridden at run time.
interface AnInterface
{
public void print();
}
abstract class Base
{
public abstract void print();
}
public class Derived extends Base implements AnInterface
{
public void print(){
System.out.println("hello");
}
AnInterface iRef = new Derived();
iRef.print(); // It means interface method is overridden and it's decided when we call the method.
Base base = new Derived();
base.print(); // It means abstract class method is overridden.
}
#Override ensures you override the method with no difference Interface or abstract superclass. So no error with override.
On the other hand Interface method is also implemented in the superclass which is enough for Interface contracts.
public class Testing extends JDialog {
public MyClass myClass;
public Testing() {
}
}
given the above code, is it possible to override a method in myClass in Testing class?
say myClass has a method named computeCode(), will it be possible for me to override it's implementations in Testing? sorry it's been a long time since I've coded.
if you want to override a method from MyClass then your testing class must extend that. for overriding a method one must complete IS-A relationship whereas your code comes under HAS-A relationship.
Yes, it is generally possible (note that as others have correctly mentioned - you'd need to extend it to override the method). Refer to this sample:
public class Animal {
public void testInstanceMethod() {
System.out.println("The instance method in Animal.");
}
}
public class Cat extends Animal {
public void testInstanceMethod() {
System.out.println("The instance method in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
myAnimal.testInstanceMethod();
}
}
Not only is it possible, but it is a key feature in polymorphism an code reusability.
Note, however, that MyClass.computeCode might be final - in this case, it cannot be overridden.
You override methods of classes that you extend. Therefore, in your example your Testing class could override the various existing methods of JDialog. If you wanted to override computeCode() from MyClass (assuming it's not final), you should make Testing extend MyClass.
public class Testing extends MyClass
{
#Override
public int computeCode()
{
return 1;
}
}
You can override a class's method only in a subclass (a class that extends the class whose method you want to override). However, given your skeletal code, you can (within Testing) have a nested class that extends MyClass and force an instance of that nested class into the myClass instance variable... so, the answer must be "yes".
Whether that's the best choice (as opposed to using interfaces, rather than subclassing concrete classes, and relying on Dependency Injection to get the implementations most suited for your testing), that's a different question (and my answer would be, unless you're testing legacy code that you can't seriously refactor until it's well test-covered... then, probably not;-).
See, if you want to override method from MyClass then you need to extend it.
As per your code, it seems you want to make a wrapper wround MyClass.
Wrapper means, calling implemented class method will call method of MyClass.
I am just clearing how wrapping works as below.
public class Testing extends JDialog {
public MyClass myClass;
public Testing() {
}
public void someMethod() {
//Add some more logic you want...
...
..
myClass.computeCode();
}
}
thanks.
The wording of the question is confused and lost.
Here are some key points:
You can't #Override something that you didn't inherit to begin with
You can't #Override something that is final
Here's a small example:
import java.util.*;
public class OverrideExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>(
Arrays.asList("a", "b", "c")
) {
#Override public String toString() {
return "I'm a list and here are my things : " + super.toString();
}
};
System.out.println(list);
// prints "I'm a list and here are my things : [a, b, c]"
}
}
Here, we have an anonymous class that #Override the toString() method inherited from java.util.ArrayList.
Note that here, it's not class OverrideExample that overrides the ArrayList.toString(); it's the anonymous class that (implicitly) extends ArrayList that does.
All the above answers are valid. But, if you want to extend JDialog but still if you want to override a method of another class it is possible through interfaces. Interfaces won't have method definitions but will have method declarations. More about interfaces, you can read at http://java.sun.com/docs/books/tutorial/java/concepts/interface.html
In your case, you can make use of interface like this
public interface MyInterface{
public void myMethod();
}
public class Testing extends javax.swing.JDialog implements MyIterface{
public void myMethod(){
// code for your method
}
}
Since Testing class has already inherited JDialog, there is no way let it inherit MyClass again unless to implement an interface. What you can do is to use some design pattern. However this is not overriding, since there is no inheritance. The Adapter is the one you need. Again you are losing the flexibility of polymorphism.
public class Testing extends JDialog {
MyClass myClass = new MyClass();
public Testing() {
}
public void methodA(){
myClass.methodA();
}
}
class MyClass {
public void methodA(){}
}