public class Cls1{
public foo(){
doX();
}
}
public class Cls2{
public foo(){
doY();
}
}
Cls2 cls = new Cls2();
cls.foo();
Is there a way to do inheritance in java that java runs both doX and doY when the user calls the function with foo?
Yes, but you have to do it explicitly:
public class Cls1{
public foo{
doX();
}
}
public class Cls2 extends Cls1 {
public foo{
super.foo();
doY();
}
}
Note: I assume you meant for Cls2 to extend Cls1, otherwise your question makes no sense at all.
public class Cls1 {
public foo{
doX();
}
}
public class Cls2 extends Cls1 {
public foo{
super.foo();
doY();
}
}
Cls2 cls = new Cls2();
cls.foo();
private class Cls2 extends Cls1 {
public void foo {
doY();
super.foo();
}
}
first of all, I assume you mean:
public class Cls2 extends Cls1{
and yes, there is:
public (something?) foo(){
super.foo();
doY();
}
The super keyword allows access to the super-class's methods. If it's simply called on its own:
super(...);
then it calls the super-class's constructor.
Assuming that Cls1 and Cls2 inherit from each other in some way, you can use the keyword super to call the superclass's implementation of a method if you want to, for instance, in the derived class perform both functions.
If doX() and doY() were statically imported (which, as they were not defined in Cls1 or in Cls2 is the only way I can think of for this program to compile), then you can make a new class with a method foo that calls doX and doY without using inheritance. Those methods named foo would have nothing to do with each other, however.
Related
I have created some interface such that:
public interface A{
}
and i would like to call the method a that I have already implemented in class B in interface A such that:
public class B{
public boolean a(){
return true;
}
}
public interface A{
public void call {
a();
}
}
without any errors, any help please?
What you want to do is strictly speaking impossible, as you cannot define method implementations in an interface. You can get something similar by defining an implementation of the interface that extends B. Hopefully that is close enough.
public class AImplementation extends B implements A{
public void call(){
a();
}
}
If you are using any java version before 8, then stick with the answers of #tinker and #Davis Broda. They provide better design since they do not couple your interface to the B class. If you insist however, in java 8 you can have default method implementations as well as static methods in an interface.
If your method is for inheritance then you have to use a default method. Add the default keyword:
default void call() {
...
}
Now the problem is how to get a reference to the class in order to call the method since you cannot have instance fields in interfaces. You have two choices:
Pass the object of B as a method parameter:
public interface A{
default void call(B b) {
b.a();
}
}
or make the method in B static
public interface A{
default void call() {
B.a();
}
}
If your method is not for inheritance but just a utility than you can make it static as :
public interface A{
public static void call() {
B.a();
}
}
I agree with #Davis Broda's answer, there is no way to have a method definition in an interface. But I have another way to address this.
You can have the interface and then have an abstract class implement this interface, and then have all other classes extend the abstract class. The abstract class doesn't have to extend the class from where you want to call the method, you could call it from an instance of that class too.
public interface A {
void caller();
}
public class B {
public void callMe() {
}
}
public class AbstractA implements A {
private B b;
public AbstractA(B b) {
this.b = b;
}
#Override
public void caller() {
b.callMe();
}
}
This way, all implementations of AbstractA will be able to call B's callMe method. And you can access this directly from the interface using this code:
A anInstance = someInstance;
anInstance.caller();
Your question is not very clear, but if I'm guessing right, you want interface A to be kind of a generic caller.
If you're using Java 8, you can achive that using a method reference:
public class B {
public boolean a() {
return true;
}
}
public interface A<T> {
default T call(Supplier<T> s) {
return s.get();
}
}
public class AImpl
implements A<Boolean> {
}
public class Sample {
public static void main(String[] args) {
AImpl a = new AImpl();
B b = new B();
boolean result = a.call(b::a);
System.out.println(result); // true
}
}
This uses Supplier<T> because your method a() in class B returns a boolean and does not receive any arguments.
I have the following classes in C++
ParentClass
{
virtual int MyMethod();
}
class ExistingOne : ParentClass {...}
class ExistingTwo : ParentClass {...}
Now I would like to create a class that can extend either of the Existing classes and override a couple of their methods plus call a method in the Existing class under some conditions.
In C++ this is done using the following:
template< class BaseTemplate >
class MyClass : public BaseTemplate
{
int MyMethod()
{
DoSomething();
return BaseTemplate::MyMethod();
}
}
How is this done in Java?
So far I have
public abstract class ParentClass
{
public abstract int MyMethod();
}
public class ExistingOne extends ParentClass {...}
public class ExistingTwo extends ParentClass {...}
public class MyClass<T extends ParentClass>
{
public int MyMethod()
{
DoSomething();
return T.MyMethod(); //MyMethod must be statically defined?
}
}
Oh and lastly, I cannot modify the "Existing" or Parent class.
So is this the correct approach? How do I solve the static requirement?
In the C++ class definition, MyClass extends BaseTemplate. In the Java example, MyClass doesn't extend ParentClass, thus getting the expected problem.
In Java, just change the definition to:
public class MyClass<T extends ParentClass> extends ParentClass {
#Override
public int MyMethod() {
DoSomething();
return super.MyMethod();
}
}
Since MyMethod is abstract in ParentClass, this gives a compiler error. Instead, you would need to call MyMethod from an instance of ParentClass. This can be fixed by having a field T t inside MyClass:
public class MyClass<T extends ParentClass> extends ParentClass {
T t;
public MyClass(T t) {
this.t = t;
}
#Override
public int MyMethod() {
DoSomething();
return t.MyMethod();
}
}
Otherwise, using generics and extending ParentClass here won't have any sense at all.
I had a doubt.
Imagine If we have a class A that implements the method
For example
private void methodA(int index) throws Exception, Error {
}
And if we have a Class B that extends the first class A.
My questions is, can class B implement
private void methodA(int index) throws Exception, Error {
}
And which method will be called under which circumstance!!
Thanks
If your methods weren't declared "private", this would just be standard polymorphism. Because they're private, the rules are a bit different. The version in class A can only be called from code that's in class A. The version in class B can only be called from code that's actually written in class B (as opposed to code that class B gets by extending class A).
YES, you can implement the methodA method in class B, but, pay attention, you are not overriding it.
Your method is declared ad private so is not "visible" from extending classes.
If your intention is to make your method overridable, you need to declare it as public.
Just give it a try :)
public class Main {
public static void main(String[] args) {
Base base;
base = new A();
System.out.println(base.doSth());
base = new B();
System.out.println(base.doSth());
}
}
abstract class Base {
public abstract String doSth();
}
class A extends Base {
#Override
public String doSth() {
return "A";
}
}
class B extends A {
#Override
public String doSth() {
return "B";
}
}
I think you wonna override the super-class method, and to do this, the method on sub-class must have the same signature of super-class method.
You can call these methods in following ways:
Suppose test1 is an instance of classA, teste1.methodA(index) will execute the implementation on super-class.
Suppose test2 is an instance of classB, test2.methodA(index) will execute the sub-class method.
In classB you can invoque the super class method (if the method is notprivate), something like :
public class ClassB extends ClassA
{
...
super.methodA(index);
...
}
I have a java program which uses arraylists - these arraylists store 'variables' where 'variables' is an abstract class.
Now, to save memory, I want to use a java library called HugeCollections-VanillaJava- however this library requires an interface to be defined.
How do I convert the abstract class into an interface? What rules/restrictions do I have to follow, to correctly perform the conversion?
Finally, is it possible for me to use my abstract class with minimal code changes, so that the library that requires an interface, also works correctly? Ideally I would like not to change the abstract class at all...Is this possible?
how do I convert an abstract class into an interface?
Make a copy of the abstract class source file.
Change "class" to "interface" in the initial declaration.
Change the name (optionally, depends on what you're doing).
Remove the bodies of any methods that are implemented by the class.
Remove the word "abstract" from the other ones.
Remove all private and protected members.
Remove all constructors.
Remove the keyword "public" from the public members.
If you had any code you removed (implemented methods, private or protected stuff), have your original abstract class implement your interface and leave that stuff there.
(Incomplete) Example:
Foo as an abstract class:
public abstact class Foo
{
private int bar;
public static final int SOME_CONSTANT = 42;
public Foo(b) {
this.bar = b;
}
public abstract void doSomething(String s);
protected int doSomethingElse() {
return this.bar * 2;
}
}
Foo as an interface:
public interface Foo
{
int SOME_CONSTANT = 42;
void doSomething(String s);
}
In my case, as I did have some stuff the old Foo did, I'd probably have AbstractFoo or something:
public abstact class AbstractFoo implements Foo
{
private int bar;
public Foo(b) {
this.bar = b;
}
public abstract void doSomething(String s);
protected int doSomethingElse() {
return this.bar * 2;
}
}
...so that an implementation could use it as a starting point if desired (although with that private bar in there, it doesn't make a lot of sense).
Pattern Adapter might help you.
Imagine, you're have to use SomeClass as TargetInterface
public abstract class SomeClass {
// some code here
public abstract void someMethod();
}
public interface TargetInterface {
public void someMethodBlaBla();
}
And they have different signatures of methods - someMethod() and someMethodBlaBla().
So you're might create such adapter class:
public class Adapter implements TargetInterface {
private SomeClass adaptee;
public Adapter( SomeClass adaptee ) {
this.adaptee = adaptee;
}
public void someMethodBlaBla() {
this.adaptee.someMethod();
}
//delegate all calls to adaptee
}
and somewhere in code you might use both - adapter and instance of abstract class, without interference on current code:
SomeClass abstractClassInstance = ... //get instance of your abstract class
TargetInterface targetInterfaceInstance = new Adapter( abstractClassInstance );
If abstract class does not define any concrete methods, you can even use regular expression for that. From:
public abstract class Abstract {
public abstract void method();
//...
}
to:
public interface Interface {
void method();
//...
}
public abstract modifiers are implicit for interfaces. If the abstract class does define some methods (not all methods are abstract) or have some fields this can't be done (at least easily).
I need a object B, but i get a object A when i execute 'B.GetByID()'
public class A
{
public A()
{
}
public static A GetSelf()
{
return new A();
}
public static A GetByID()
{
return GetSelf();
}
}
public class B extends A
{
public B()
{
super();
}
public static B GetSelf()
{
return new B();
}
}
B.GetByID(); //returns A, i need B
You can only do that by also creating a B GetByID() method in B. That's somewhat ugly though...
Basically your B.GetByID() call will be resolved to A.GetByID(); nothing in the compiled code will indicate that it was originally B.GetByID(), and the call to GetSelf() within GetByID() will be resolved to A.GetSelf() anyway.
Basically, static methods don't allow for polymorphism in the way you want. I suggest you create an AFactory and a BFactory subclass, and use method overriding in the normal way, with instance methods.
You could add a GetByID method to B, like so:
public class B ... {
public static B GetByID()
{
return GetSelf();
}
}
Your factory method (no matter in which class it's declared) needs to be aware of both, A and B and then make a decision on which class to instantiate. If the caller knows it needs a B, it just can do a new B() anyway, so the factory method has no value there anyway.