Say I have the following classes:
abstract class A {
abstract public void methodA();
}
class B extends A {
#Override
public void methodA(){
}
}
And then I use methodA() somewhere else with implementation of class B. In Android Studio, when I opened class A in editor, it gave me the warning that method methodA() is never used. Why is that so?
Related
When the functional interface is in the same file where lambda overrides it, it compiles fine.
package test.test;
public class Base {
public static void main(String[] args) {
Interface1 a = n -> System.out.println(2*n);
}
}
interface Interface1 {
void multiplyByTwo(int x);
}
When the functional interface is in a separate file and Base class implements it, it fails to compile with Base is not abstract and does not override abstract method multiplyByFour(int) in Interface3 error.
package test.test;
public class Base implements Interface3 {
public static void main(String[] args) {
Interface3 b = n -> System.out.println(4*n);
}
}
package test.test;
public interface Interface3 {
void multiplyByFour(int x);
}
Is here something wrong? Why does lambda not override the method in the second case?
Your first example has:
public class Base {
which does not implement Interface1
However, your second example has:
public class Base implements Interface3 {
which DOES implement Interface3
Not sure what you are trying to do here, but this is intended behaviour:
Interfaces
When a class implements an interface, you must implement all of the methods into the class
For example:
public interface IFoo {
void bar();
}
and class:
public class FooImpl implements IFoo {
// must implement bar method in IFoo
public void bar() {
System.out.println("I did something");
}
}
Having a lambda in the main method does not constitute implementing interface methods.
Fix?
Just delete implements Interface3, you don't need to implement the interface in your class to be able to use it.
Consider the following:
//Fooable.java
public interface Fooable {
public default void foo() {
System.out.println("Fooable::foo");
}
//Lots of other non-default methods...
}
//MyFooable.java
public class MyFooable implements Fooable {
#Override
public void foo() {
System.out.println("MyFooable::foo");
}
//implements other methods in Fooable...
}
//MyAdvancedFooable.java
public class MyAdvancedFooable extends MyFooable {
#Override
public void foo() {
Fooable.super.foo();
System.out.println("MyAdvancedFooable::foo");
}
public static void main(String[] args) {
new MyAdvancedFooable().foo();
}
}
As you can see, I want to call foo() in Fooable from MyAdvancedFooable (a subclass of MyFooable). However, when I try to compile, I get the following error:
MyAdvancedFooable.java:4: error: not an enclosing class: Fooable
Fooable.super.foo();
if I try MyAdvancedFooable extends MyFooable implements Fooable I get the following:
MyAdvancedFooable.java:4: error: bad type qualifier Fooable in default super call
Fooable.super.foo();
method foo() is overridden in MyFooable
How can I resolve this problem without having to create a new anonymous implementation of Fooable?
You can only call a method one level up so you would need
Fooable.super.foo();
in MyFooable, while just calling super.foo() in MyAdvancedFooable
You need to use just super.foo() or this.super.foo() as it is the parent of the object and not of the class as implied by Fooable.super.foo().
I have 3 classes. It seems basic question. But I can'nt find answer by googling.
public abstract class Test {
void t1()
{
System.out.println("super");
}
}
public class concret extends Test{
void t1()
{
System.out.println("child");
}
void t2()
{
System.out.println("child2");
}
}
public class run {
public static void main(String[] args) {
Test t=new concret();
t.t1();
}
}
How do I call abstract class t1 method? Since I cant create object from abstract class how do I call t1 in abstract class?
Thank you.
Either you create a concrete class which doesn't override the method, or within a concrete class which does override the method, you can call super.t1(). For example:
void t1()
{
super.t1(); // First call the superclass implementation
System.out.println("child");
}
If you've only got an instance of an object which overrides a method, you cannot call the original method from "outside" the class, because that would break encapsulation... the purpose of overriding is to replace the behaviour of the original method.
you should be able to do it using
Test test = new Test(){};
test.t1();
Abstract class means the class has the abstract modifier before the class keyword. This means you can declare abstract methods, which are only implemented in the concrete classes.
For example :
public abstract class Test {
public abstract void foo();
}
public class Concrete extends Test {
public void foo() {
System.out.println("hey");
}
}
See following tests:
public abstract class BaseClass {
public void doStuff() {
System.out.println("Called BaseClass Do Stuff");
}
public abstract void doAbstractStuff();
}
public class ConcreteClassOne extends BaseClass{
#Override
public void doAbstractStuff() {
System.out.println("Called ConcreteClassOne Do Stuff");
}
}
public class ConcreteClassTwo extends BaseClass{
#Override
public void doStuff() {
System.out.println("Overriding BaseClass Do Stuff");
}
#Override
public void doAbstractStuff() {
System.out.println("Called ConcreteClassTwo Do Stuff");
}
}
public class ConcreteClassThree extends BaseClass{
#Override
public void doStuff() {
super.doStuff();
System.out.println("-Overriding BaseClass Do Stuff");
}
#Override
public void doAbstractStuff() {
System.out.println("Called ConcreteClassThree Do Stuff");
}
}
public class Test {
public static void main(String[] args) {
BaseClass a = new ConcreteClassOne();
a.doStuff(); //Called BaseClass Do Stuff
a.doAbstractStuff(); //Called ConcreteClassOne Do Stuff
BaseClass b = new ConcreteClassTwo();
b.doStuff(); //Overriding BaseClass Do Stuff
b.doAbstractStuff(); //Called ConcreteClassTwo Do Stuff
BaseClass c = new ConcreteClassThree();
c.doStuff(); //Called BaseClass Do Stuff
//-Overriding BaseClass Do Stuff
c.doAbstractStuff(); //Called ConcreteClassThree Do Stuff
}
}
use keyword 'super' to do that
void t1()
{ super.t1();
System.out.println("child");
}
Make sure you use that in the overriden method though.
Your code seems to call t1(). However this is calling the concrete t1() because the abstract t1() has been overridden by the concrete class.
If you wish to call the abstract t1 method from main code, do not override the t1() in concrete.
Or you can create a method in the concrete class for example:
public void invokeSuperT1(){
super.t1();
}
Create an anonymous Inner class,
Abstract class:
abstract class Test{
abstract void t();
public void t1(){
System.out.println("Test");
}
}
Here is how to create anonymous inner class:
Test test = new Test() {
#Override
void t() {
//you can throw exception here, if you want
}
};
Call the class via the object created for abstract class,
test.t1();
An abstract class is used when we want that every class that inherited from our abstract class should implement that abstract method, so it is must to implement method otherwise it gives the compile-time error.
void t1()
{
super.t1; // means the parent methods
System.out.println("child");
}
For example: Bird class has method sing() and there other classes that inherited from it like the sparrow, Pigeon, Duck, so these all have sing method so we make Bird class Abstract and make the sing() method abstract in it so every child of bird that implements Bird class should have a method of sing() with its on implementation.
First Create abstarct class like as shown in link: Creating Abstract Class
Create Sub-Classs like as shown in link: Sub-class extending
Creating main method for executing this as show in link: Instanciate the subclass to access
Result as shown here: Result
Greetings and salutations!
I currently have an abstract class A, and many classes subclassing it. The code is common to all the subclasses I've put in the oneMethod() and the code that's specific to each implementation I've put into two abstract methods.
public abstract class AbstractA {
public oneMethod() {
//do some intelligent stuff here
abstractMethodOne();
abstractMethodTwo();
}
protected abstract void abstractMethodOne();
protected abstract void abstractMethodTwo();
}
I have a class that overrides the oneMethod() method.
public class B extends AbstractA {
#Override
public oneMethod() {
//do some other intelligent stuff here
}
}
Is there any way to skip making a stub implementation of the two abstract methods in the subclass? I mean the only place they're used is in the overridden method.
Any help is appreciated!
No. If you extend an abstract class, you must either make the child class abstract or it must fulfill the contract of the parent class.
As a design observation, I would suggest that you try to make oneMethod() either final or abstract. It's hard to maintain programs that allow extension the way you're implementing it. Use other abstract methods to give child classes hooks into the functionality of oneMethod().
You have to provide an implementation to all abstract methods. Even if no part of the program calls them now a class can be created in the future that does call them, or the super class implementation may be changed. A stub is needed even if it's just for binary compatibility.
Just make class B also abstract.
public abstract class B extends AbstractA {
You could pull oneMethod up into a superclass:
public abstract class AbstractC {
public void oneMethod() {
}
}
public abstract class AbstractA extends AbstractC {
#Override
public void oneMethod() {
//do some intelligent stuff here
abstractMethodOne();
abstractMethodTwo();
}
protected abstract void abstractMethodOne();
protected abstract void abstractMethodTwo();
}
public class B extends AbstractC {
#Override
public void oneMethod() {
//do some other intelligent stuff here
}
}
see now how you don't need any more in AbstractC than you need.
Since abstractMethodOne() and abstractMethodTwo() are implementation specific but you know that you will always call them you can use composition like this:
public interface SomeInterface {
void abstractMethodOne();
void abstractMethodTwo();
}
and create a class like this:
public class SomeClass {
public void executeThem(SomeInterface onSomeObject) {
onSomeObject.abstractMethodOne();
onSomeObject.abstractMethodTwo();
}
}
then you can compose this in any of your classes where you should call those methods like this:
public class SomeImplementation implements SomeInterface {
public void abstractMethodOne() {
// ...
}
public void abstractMethodTwo() {
// ...
}
public void executeThem() {
new SomeClass().executeThem(this);
}
}
This way you got rid of the inheritance altogether and you can be more flexible in your classes implementing SomeInterface.
If your classes B and A have to implement their own oneMethod it's maybe because there are not in an inheritance link but they just should implement the same interface ?
Well, if abstractMethodTwo and abstractMethodOne are implementation specific, why you put these methods in the base abstract class ? Maybe a common interface or some specific design-pattern is what you're looking for!
An abstract method from an abstract class can be used in a class in the way shown below. I would appreciate your opinion if you find any wrong in my answer. Thank you.
Code using Java
public abstract class AbstractClassA {
protected abstract void method1();
public abstract void method2();
}
public class ClassB extends AbstractClassA{
#Override
protected void method1(){}
public void method2(){}
}
Let's say I have three classes A, B and C.
B extends A
C extends B
All have a public void foo() method defined.
Now from C's foo() method I want to invoke A's foo() method (NOT its parent B's method but the super super class A's method).
I tried super.super.foo();, but it's invalid syntax.
How can I achieve this?
You can't even use reflection. Something like
Class superSuperClass = this.getClass().getSuperclass().getSuperclass();
superSuperClass.getMethod("foo").invoke(this);
would lead to an InvocationTargetException, because even if you call the foo-Method on the superSuperClass, it will still use C.foo() when you specify "this" in invoke. This is a consequence from the fact that all Java methods are virtual methods.
It seems you need help from the B class (e.g. by defining a superFoo(){ super.foo(); } method).
That said, it looks like a design problem if you try something like this, so it would be helpful to give us some background: Why you need to do this?
You can't - because it would break encapsulation.
You're able to call your superclass's method because it's assumed that you know what breaks encapsulation in your own class, and avoid that... but you don't know what rules your superclass is enforcing - so you can't just bypass an implementation there.
You can't do it in a simple manner.
This is what I think you can do:
Have a bool in your class B. Now you must call B's foo from C like [super foo] but before doing this set the bool to true. Now in B's foo check if the bool is true then do not execute any steps in that and just call A's foo.
Hope this helps.
To quote a previous answer "You can't - because it would break encapsulation." to which I would like to add that:
However there is a corner case where you can,namely if the method is static (public or protected). You can not overwrite the static method.
Having a public static method is trivial to prove that you can indeed do this.
For protected however, you need from inside one of your methods to perform a cast to any superclass in the inheritance path and that superclass method would be called.
This is the corner case I am exploring in my answer:
public class A {
static protected callMe(){
System.out.println("A");
}
}
public class B extends A {
static protected callMe(){
System.out.println("B");
}
}
public class C extends B {
static protected callMe(){
System.out.println("C");
C.callMe();
}
public void accessMyParents(){
A a = (A) this;
a.callMe(); //calling beyond super class
}
}
The answer remains still No, but just wanted to show a case where you can, although it probably wouldn't make any sense and is just an exercise.
Yes you can do it. This is a hack. Try not to design your program like this.
class A
{
public void method()
{ /* Code specific to A */ }
}
class B extends A
{
#Override
public void method()
{
//compares if the calling object is of type C, if yes push the call to the A's method.
if(this.getClass().getName().compareTo("C")==0)
{
super.method();
}
else{ /*Code specific to B*/ }
}
}
class C extends B
{
#Override
public void method()
{
/* I want to use the code specific to A without using B */
super.method();
}
}
There is a workaround that solved my similar problem:
Using the class A, B, and C scenario, there is a method that will not break encapsulation nor does it require to declare class C inside of class B. The workaround is to move class B's methods into a separate but protected method.
Then, if those class B's methods are not required simply override that method but don't use 'super' within that method. Overriding and doing nothing effectively neutralises that class B method.
public class A {
protected void callMe() {
System.out.println("callMe for A");
}
}
public class B extends A {
protected void callMe() {
super.callMe();
methodsForB(); // Class B methods moved out and into it's own method
}
protected void methodsForB() {
System.out.println("methods for B");
}
}
public class C extends B {
public static void main(String[] args) {
new C().callMe();
}
protected void callMe() {
super.callMe();
System.out.println("callMe for C");
}
protected void methodsForB() {
// Do nothing thereby neutralising class B methods
}
}
The result will be:
callMe for A
callMe for C
It's not possible, we're limited to call the superclass implementations only.
I smell something fishy here.
Are you sure you are not just pushing the envelope too far "just because you should be able to do it"? Are you sure this is the best design pattern you can get? Have you tried refactoring it?
I had a problem where a superclass would call an top class method that was overridden.
This was my workaround...
//THIS WOULD FAIL CALLING SUPERCLASS METHODS AS a1() would invoke top class METHOD
class foo1{
public void a1(){
a2();
}
public void a2(){}
}
class foo2 extends foo1{
{
public void a1(){
//some other stuff
super.a1();
}
public void a2(){
//some other stuff
super.a2();
}
//THIS ENSURES THE RIGHT SUPERCLASS METHODS ARE CALLED
//the public methods only call private methods so all public methods can be overridden without effecting the superclass's functionality.
class foo1{
public void a1(){
a3();}
public void a2(){
a3();}
private void a3(){
//super class routine
}
class foo2 extends foo1{
{
public void a1(){
//some other stuff
super.a1();
}
public void a2(){
//some other stuff
super.a2();
}
I hope this helps.
:)
Before using reflection API think about the cost of it.
It is simply easy to do. For instance:
C subclass of B and B subclass of A. Both of three have method methodName() for example.
public abstract class A {
public void methodName() {
System.out.println("Class A");
}
}
public class B extends A {
public void methodName() {
super.methodName();
System.out.println("Class B");
}
// Will call the super methodName
public void hackSuper() {
super.methodName();
}
}
public class C extends B {
public static void main(String[] args) {
A a = new C();
a.methodName();
}
#Override
public void methodName() {
/*super.methodName();*/
hackSuper();
System.out.println("Class C");
}
}
Run class C Output will be:
Class A
Class C
Instead of output:
Class A
Class B
Class C
In my simple case I had to inherit B and C from abstract class, that incapsulates equal methods of B and C. So that
A
|
Abstr
/ \
B C
While it doesn't solve the problem, it can be used in simple cases, when C is similar to B. For instance, when C is initialized, but doesn't want to use initializers of B. Then it simply calls Abstr methods.
This is a common part of B and C:
public abstract class Abstr extends AppCompatActivity {
public void showProgress() {
}
public void hideProgress() {
}
}
This is B, that has it's own method onCreate(), which exists in AppCompatActivity:
public class B extends Abstr {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Call from AppCompatActivity.
setContentView(R.layout.activity_B); // B shows "activity_B" resource.
showProgress();
}
}
C shows its own layout:
public class C extends Abstr {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Call from AppCompatActivity.
setContentView(R.layout.activity_C); // C shows "activity_C" resource.
showProgress();
}
}
This is not something that you should do normally but, in special cases where you have to workaround some bug from a third party library (if it allow to do so), you can achieve calling a super super class method that has already been overwritten using the delegation pattern and an inner class that extends the super super class to use as a bridge:
class A() {
public void foo() {
System.out.println("calling A");
}
}
class B extends A() {
#Overwrite
public void foo() {
System.out.println("calling B");
}
}
class C extends B() {
private final a;
public C() {
this.a = new AExtension();
}
#Overwrite
public void foo() {
a.foo();
}
private class AExtension extends A {
}
}
This way you will be able to not only call the super super method but also combine calls to other super super class methods with calls to methods of the super class or the class itself by using `C.super` or `C.this`.