How can i call an non static method of Abstract class, without using its sub class or extends it because abstract class and sub class is too complex so i do not want to cause any side effect.
for example concrete static methods of an abstract class can be call with class name an dot operator, without creating sub class. Similar is there any way to call a non static method.
i just want to run a method and i do not want run any other code. i tried to use reflection but it requires instance
Abstract classes are abstract, meaning that you cannot create an instance of the class.
Therefore, you cannot call instance methods of an abstract class.
public abstract class Foo {
static void bar();
void foobar();
}
you can call Foo.bar() as it is not an instance method (meaning that it does not require an instance of the class) but you cannot call foobar() since you cannot do new Foo().foobar().
Foo.bar(); // OK, we don't need an instance.
Foo foo = new Foo(); // Not OK - we cannot instantiate an abstract class.
foo.foobar();
For a way to create an instance of an abstract class without having to use derived classes, see ernest_k's answer utilizing anonymous classes.
The short answer is that you can't. You need an instance.
An easy way to create an instance is using an anonymous class:
AbstractClass o = new AbstractClass(){
//implement abstract methods... or just leave stubs
};
o.concreteMethod();
Related
I am making changes to a Java class of ours, and I noticed the following line of code:
OurClass<OurInterface1> ourClass = new OurClass<OurInterface1>() {};
What I find strange about that line is that OurClass is an abstract class - here's the definition of OurClass:
public abstract class OurClass<T extends OurInterface1> implements OurInterface2<T>
When I remove the {} at the end of the line, Eclipse tells me Cannot instantiate the type OurClass<OurInterface1>, but when I put the {} back, everything is OK.
How does {} allow you to instantiate an abstract class?
Adding the {} introduces the syntax for an anonymous inner class.
The anonymous class expression consists of the following:
The new operator
The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.
Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
You are declaring an anonymous inner class that subclasses OurClass. The body of this class is empty: {}. This anonymous inner class is not abstract, so you are able to instantiate it.
When you remove the {}, the compiler thinks that you are directly instantiating OurClass, an abstract class, so it disallows it.
You can actually extend and override methods on the fly when you instantiate off an interface or extendible class. This is called an anonymous inner class.
What you did in your example is create an anonymous inner class, but it had no effect because you didn't override anything. You could have put overridden methods in those curly brackets {}.
OurClass<OurInterface1> ourClass = new OurClass<OurInterface1>() {};
A commonly applied use of anonymous inner class is on the Runnable interface, which defines a single void run() method. You can implicitly instantiate an object that implements Runnable and override run() on the fly.
Runnable someTask = new Runnable() {
#Override
public void run() {
System.out.println("Running a task!");
}
};
Anonymous inner classes are disliked by a lot of developers because they are pretty verbose. Fortunately in Java 8, you can use lambda expressions to replace most anonymous inner classes that implement a single method. The compiler infers the anonymous inner class for you basically, allowing you to write the code more concisely.
Runnable someTask = () -> System.out.println("Running a task!");
The block after the call to the new operator (new OurClass<OurInterface1>() {}) is infact creating an instance of an anonymous class which extends OutClass.
Since this class is no longer abstract, there's no problem to instantiate it.
You cannot instantiate an abstract class without implementing the abstract functions within the class. This is usually done by instatiating abstract classes with implemented class.
Refer: https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
In your case, the {} used after the instantiation allows you to implement any of the abstract functions in the abstract class.
For example,
Consider
public abstract class DummyClass {
abstract void test() ;
}
is the abstract class with a abstract function.
The class can be initiated by:
DummyClass d = new DummyClass(){
void test(){
//test() implementation here
}
} ;
Hope this helps! :)
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();
Java allows to define the following pair of classes.
class Class1 { ... }
public Class2 { public Class2(Class1 c1) { ... } }
Why Class2 has public constructor if I cannot instantiate it because Class1 is not accessible?
For the record, there are no public classes that inherit from Class1.
Class1 and Class2 are defined in same package. So they can be accessible. Class1 has default access modifier, which is visible to all Classes inside the same package
At the first glance, it seems like it does not make sense: A user of this package may access Class2. But he can't create an instance of Class2, because he has no access to Class1. So there is no reason of making the constructor public, when the argument that it needs is not public as well.
The only situation where this actually makes sense is when there is another public class in the same package that extends Class1. Then you could create an instance of this class, and pass it to the constructor:
// Assuming this class extends Class1, and it is public, you
// can create an instance of this class from outside the package:
ExtendedClass1 e = new ExtendedClass1();
// This is using the public constructor that expects a Class1.
// Although Class1 itself is NOT public, this constructor
// can be called with an instance of a (public) class that
// extends Class1
Class2 c = new Class2(e);
But since the latter was excluded in the question, there is no reason to have this public constructor.
It is reasonable to have a class that limits its creation/access to members of the same package with a view that other classes in the same package will extend this class and be made public.
For example if you were implementing the Template pattern you might have super class (probably abstract) that implemented the base, shared, logic, with one or more concrete classes that implemented the the differing steps.
These concrete classes could then be instantiated by callers, but the base class wouldn't.
Arguably though the base class could equally be protected instead of package scope.
Every class has a default constructor(if you do not provide one) you can do :
Class1 c1 = new Class1();
then
Class2 c2 = new Class2(c1);
Hi I have an abstract class which have many subclasses. Id like to make this abstract class' constrcutor private and create factory method. How should this method look like to work in the same way in every sub-class? If I make:
return new AbstractClass();
I get error saying: Class is abstract, cannot be instances... Should I use reflection?
You can access the constructor of the abstract class from the subclasses using the super keyword.
public SubClass() {
super(); // this will call AbstractClass()
// something else that you want to do for this subclass
}
As already pointed out in the comments, you can't use the new keyword with an abstract class. When you use new, you need to know the real type.
You could either implement the factory method in the abstract base class and make it decide which non-abstract subclass to return based on the parameters passed to the create method and/or some internal logic.
Or you could make the factory method itself abstract and implement it in every non-abstract subclass to return an object of that type.
In Java Interface, we can have only final variables possible. We can also create static variables in Interface. But, at the same time we are not able to create static/final methods as Interface are only meant for Static Methods.
What is exactly the reason for not allowing static/final methods in Interface ?
A final method can't be overridden. That defies the purpose of having an interface if you cannot actually implement the method.
For the static part, see this question.
You got it wrong.
All variables are implicitly public static and final in interfaces.
Prior to Java 8, you can't create static methods in interfaces. All methods are instance methods.
Since the only goal of an interface is to have classes implementing them, and since methods in interfaces can't have any implementation, making them final would make no sense: they would have no implementation, and could not be overridden.
Interfaces are defined for instances, not statics.
"final" means "can't be overridden". That makes no sense for an interface whatsoever.
final means that it cannot be overriden.
static means that it can only be called using the class name. Since an interface will have multiple implementations, how will you know which implementation to choose since the interface cannot implement the method itself?
Because they are there in an interface to be implemented by some class. What would be the point of a method that can not have an implementation anywhere? (which is what final would suggest)
I have one more point to prove why interface methods can not be static :
interface MyInterface {
static void myStaticMethod();
}
Now let's have two classes are implementing "MyInterface"
// first class
class MyClass1 implements MyInterface {
static void myStaticMethod(){
// some implementation
}
}
// second class
class MyClass2 implements MyInterface {
static void myStaticMethod(){
// some implementation
}
}
Now I am instantiating like below:
1- MyInterface myObj1 = new MyClass1();
2- myObj1.myStaticMethod();
3- MyInterface myObj2 = new MyClass2();
4- myObj2.myStaticMethod();
// here at line 2 & 4 , it's wrong calling as myStaticMethod should be called using class name(because myStaticMethod is defined as static) like below:
MyInterface.myStaticMethod();--> But in this case,how to call different implementations of myStaticMethod() by MyClass1 & MyClass2 classes.
So it's proved that static can not be possible in interface method declaration.
For final ,it's quite clear that it will opposite to override functionality.
An interface is a pure abstract class. Hence, all methods in an interface are abtract, and must be implemented in the child classes. So, by extension, none of them can be declared as final.
Why Interface methods cannot be “static” & “final”?
All methods in an interface are explicitly abstract and hence you cannot define them as static or final because static or final methods cannot be abstract.
In the context of Java 8 and default methods, this question has a new meaning. static methods are now allowed, and why final methods still aren't possible is explained in this question.
1: we can't declare a final method ,because it contradicts it's rule as final method can't be override,but always need to define all the interface methods in it implemented classes.
2: we can't declare a static method ,because it contradicts it's rule as static method always needs the method body but we cant define any method inside a interface.
Well static methods work on classes and not instances so kind of strange/pointless. Having said that I've for one reason or another wanted this in some situations, though can't remember a case now so must have been long ago.
You can "work around" this though (rather alternative api design) as interfaces allow you to declare classes, so something like this:
interface MyInterface {
static class Helpers {
static void myStaticMethod(); //can be abstract etc as usual
}
}
You can subclass that class etc as normal of course, as well make it abstract, abstract methods etc etc.
We can not declare method of interface as static because method of interface instance method and we can not declare final because it is necessory to override method of interface in implemented class. for description check this link enter link description here
By default all the methods present inside an interface are public and abstract. If you declair a method as final inside an interface 1st of all you will get a compiler error and not even then it doesn't make any sense to have a final method because you will never be in a position to override it in child class.
In case of static even if Java allow in what so ever version it's not a good programming practice to use static inside an interface because for static methods u must have to provide the implementation which you must not provide inside an interface. Moreover, even if you provide the implementation inside an interface still u have to override it and then have to call it by the class name.
Interface cant have static method because if you know the static property that method declared static can be called without creating any object of class and sttaic methods are part of class not instance of class, so the answer is that how can you call abstract method till java 7, In java 8 you can declare method as static and call it by interface name dot method name.
Now answer fo final is that , final method is not overriden so how you will override it when class will inherit it
why can't we make Interface methods final?
because if you make a method final then you can not override it and the sole purpose of Interface is to have methods that will be overridden by all those class that implements that Interface.
why can't we make Interface methods static?
In Java 8 it's possible, you can make methods static but that method should have a method body
interface Test{
static void hello(){
System.out.println(“hello world”);
}
}
and you can access this method from a class implementing this Interface by
Test.hello();