I know that we can write main method in abstract class, but what we can achieve from it ?
public abstract class Sample
{
public static void main(String args[])
{
System.out.println("Abstract Class main method : ");
}
}
We can not create the object of abstract class ,so what is the use of main method in abstract class ?
Abstract just means you can't instantiate the class directly.
Loading a class is not the same as creating an instance of the class. And there's no need to create an instance of the class to call main(), because it's static. So there's no problem.
Abstract just means you can't instantiate the class directly. You can have constructors if you want - they might be needed for subclasses to initiate the object state. You can have static methods, including main() and they don't need an object so calling them is fine.
So you only got error when you try to create the object, which is when you run into the abstract limitation.
You can extend the abstract class and then the child class has a main method without specifying one there.
public abstract class Abstrc
{
Abstrc(){} // constructor
public abstract void run(); // abstract method
public static int mul(){return 3*2;} // static method
public static void main(String[] args)
{ // Static method that can be accessed without instantiation
System.out.println("Your abstract no is : " + Abstrc.mul());
}
}
Your abstract no is : 6
As Zeeshan already said, since the main method is static, it does not require an instance to be called. As to what can be achieved by placing the main method in an abstract class, well nothing more or less than placing it in any other class.
Typically, the main method is either placed in a class of its own or in a class that is central to the application. If that class happens to be abstract, so be it.
Related
package javaPrac;
abstract public class Abstract_class_method {
abstract void show(); //abstract methods requires abstract class and has no method .
void calculate(int x, int y)
{
int calc = x + y;
System.out.println("This is the normal method in abstract class "+calc);
}
//As per my knowledge there is no point of creating the main method within the abstract class as we cant able to create an object of the abstract class , so we either we need to use the extend keyword to extend it to other class or use the interface.
public static void main(String[] args) {
Abstract_class_method abobject = new Abstract_class_method() {
#Override
void show() {
// TODO Auto-generated method stub
System.out.println("This is the main method");
}
};
abobject.show();
abobject.calculate(10, 12);
}
}
output
This is the main method
This is the normal method in abstract class 22
I am unable to understand the working of the main method as how in the main method I can able to make the object of the abstract class , correct me if I am wrong as the similar functionality is been observed when I am on working on anonymous classes in java.
Please provide explanation of the above code.
You help is highly appreciated.
Abstract classes are classes that a programmer intentionally designates as "incomplete". They are usually used for convenience - i.e. to provide a quick way of building your own class on top of something existing with minimal effort, and to hold the code that would normally be shared among all subclasses.
What you are doing is:
You have defined an abstract class, which by definition cannot be instantiated with new(). This class is missing a show() method, but provides a calculate() method.
In your main() method you are creating an anonymous subclass of your abstract class that actually implements the missing show() method. It also inherits calculate() method from its parent class.
Okay, people are probably going to run to flag this as a duplicate, just by reading the title and without really reading the question. So please know that I HAVE tried to look at other questions on this platform, but have not found something that clears my doubts exactly. Kindly allow me to reach out and ask my question. Thanks in advance.
Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
I do not completely understand the latter part of the statement. Is this talking about the main method being directly within the abstract class itself ? Is it talking about invoking the abstract class via a child's main method ? Or both ?
Secondly, I have seen examples like the following.
abstract class Printer
{
public void print() { … };
}
public class TestPrinter
{
public static void main( String[] args )
{
// use of anonymous class
final Printer p = new Printer()
{
#override
public void print()
{
...
}
}
}
}
And have been told that an anonymous class is at work. But, I seriously do not understand how, since the variable 'p' is clearly being assigned to... and it's an abstract class variable!! How is that even possible? I thought abstract classes can not be instantiated or initialized.
Any help would be appreciated.
final Printer p = new Printer()
{
#override
public void print()
{
...
}
}
This means that an anonymous class is created which extends Printerand the variable p is referring to subclass instance.
This is simply polymorphism in action. By creating anonymous class here, you are creating a subclass of Printer and using polymorphism you are using the superclass reference variable p to refer to object of subclass which is anonymous but extends Printer because of the syntax below
Printer p = new Printer(){...}
and this is not only limited to abstract class, you can also create an anonymous class which implements and interface. Consider below example.
package com.test;
public interface SomeInterface {
public void SomeMethod();
}
and a class below
package com.test;
public class TestAnonymous {
public static void main(String[] args) {
SomeInterface obj = new SomeInterface() {
#Override
public void SomeMethod() {
System.out
.println("Yaayy!!! Creating an anonymous class which implements SomeInterface ");
}
};
obj.SomeMethod();
}
}
which prints out
Yaayy!!! Creating an anonymous class which implements SomeInterface
What is means that the syntax creates an anonymous class which either extends the abstract class or implements the interface of which reference variable is used to instantiate. It calls method of the subclass.
You can refer jsl.https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.1
Now your question
Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists
What I understand from your questions is whether you want to know whether main method can be run in abstract class without instantiating it, The answer is YES
package com.test;
public abstract class AbstractClass {
public static void main(String[] args) {
System.out.println("main method in abstract class");
}
}
compile and invoke it using java AbstractClass and it should print
main method in abstract class
IF you want to know whether the abstract class constructor is invoked when instantiating the anynomous class or not, then also the answer is YES.
Whenver a subclass constructor is called, it invokes super class constructor by making a super() call. So abstract class constructor will also get called.
http://www.thejavageek.com/2013/07/21/initialization-blocks-constructors-and-their-order-of-execution/
An abstract class is just like any other class - except for the fact that it cannot be instantiated directly. I presume you know the use for such a facility. Hence it can very well have a main(), which is a static method, not an instance method
The anonymous class in your example, extends the abstract class (or implements an interface, if one is specified). So p is not assigned to an abstract class instance, but to an instance of a class which extends the abstract class
A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
It is nonsense. Any static method of an abstract class can be invoked. Not just main().
Secondly, I have seen examples like the following ... and have been told that an anonymous class is at work.
That is correct.
But, I seriously do not understand how, since the variable 'p' is clearly being assigned to... and it's an abstract class variable!! How is that even possible? I thought abstract classes can not be instantiated or initialized.
It is the anonymous class that is being instantiated here, which extends the abstract class, and provides an implementation of the abstract method. The reference to that class is being stored into Person p, because Person is a superclass of the anonymous class. You can do that for any other class or interface. There's nothing new here.
A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
Since main() method is static an can be invoked without instantiation. e.g.
abstract class AbstractClass{
public static void main(String[] args){
}
}
The same was not true for interface till Java7, With Java8 you can have static main method inside interface hence same would be true for Java8
You second question, while creating an instance of Printer you have defined the sub-class of Printer as well but you can not use this defined implementation of Printer again(since there is no name associated with the implementation), Hence, its anonymous.
Would using a main for an abstract class be bad practice in general or is it permissible due to the nature of Abstract classes being able to have a body?
Sure, an abstract class can have a main method, just as any class can have a main, and in fact it is one way of testing the abstract class -- if you create a concrete implementation of it within the main method. The only thing that you cannot do with an abstract class is to construct them as is, without extending them and implementing all abstract methods.
public abstract class Foo {
public abstract void bar();
public static void main(String[] args) {
// anonymous inner class representation
Foo foo = new Foo() {
// must implement all abstract methods
public void bar() {
System.out.println("bar");
}
};
foo.bar();
}
}
Edit: good point by VitalyGreck:
abstract classes are abstract because they don't implement some methods in their body. having bar() implemented inside the main() method (even static) confuses users of your class. Good practice is to make two separate classes, one of them - abstract, another - with implementation and static method enclosed. Or dynamically find the enclosing class (see stackoverflow.com/questions/936684/…) using reflection.
In other words -- just because it can be done, doesn't mean that it should be done.
You have no problemas having a main in your abstract class.
Static methods does not override, any subclass can also have the same static method.
In Java Programming, Can we call a static method of an abstract class?
Yes I know we can't use static with a method of an abstract class. but I want to know why.. ?
In Java you can have a static method in an abstract class:
abstract class Foo {
static void bar() { }
}
This is allowed because that method can be called directly, even if you do not have an instance of the abstract class:
Foo.bar();
However, for the same reason, you can't declare a static method to be abstract. Normally, the compiler can guarantee that an abstract method will have a real implementation any time that it is called, because you can't create an instance of an abstract class. But since a static method can be called directly, making it abstract would make it possible to call an undefined method.
abstract class Foo {
abstract static void bar();
}
// Calling a method with no body!
Foo.bar();
In an interface, all methods are implicitly abstract. This is why an interface cannot declare a static method. (There's no architectural reason why an interface couldn't have a static method, but I suspect the writers of the JLS felt that that would encourage misuse of interfaces)
If you are talking about java, answer is Yes But you need to define the static method. You cannot create an abstract static method. What you can create is non abstract static method.
Reason is you do not need a object instance to access a static method, so you need the method to be defined with a certain functionality.
so you cannot have,
abstract class AbstractClassExample{
abstract static void method();
}
But you can have,
abstract class AbstractClassExample{
static void method(){}
}
Hope this helps...
Here is a simple explanation.Abstract methods must be implemented later.We know that static methods cannot be overridden because static methods do not belong to any particular instance, rather it belongs to the class.Then different implementation of abstract method,which is static, in different classes is counter-intuitive.
Yes, of course you can define the static method in abstract class.
you can call that static method by using abstract class,or by using child class who extends the abstract class.Also you can able to call static method through child class instance/object.
To illustrate further test following example.
//Parent class
public abstract class TestAbstractClass {
static void testStaticMethod(){
System.out.println("In Parent class static method");
}
}
//child class
public class ChildClass extends TestAbstractClass {
public static void main(String[] args) {
TestAbstractClass parentObj = new ChildClass();
parentObj .testStaticMethod();
ChildClass childObj = new ChildClass();
childObj.testStaticMethod();
TestAbstractClass.testStaticMethod();
childClass.testStaticMethod();
}
}
From Java 9 onwards you can have static methods in an interface. However, the implementation must be provided in the block itself. Unlike static methods in a class, a static method in an interface is not inherited by implementation through a class or subinterface.
An abstract can contain a static method. It is because a static method though not overridden can be hidden.
But an abstract method cannot be declared static at the same time as an abstract method must be overridden ans implemented by a subclass's method and declaring it static will prevent overriding.
In other words, you cannot use abstract and static keywords to declare the same method. However, you can have a static method inside an abstract class.
I am developing a webApplication based on Java EE.
I have an abstract class, in which I need to have a one-time operation (a database call).
So below in the sample code, I pasted it inside its constructor, but don't know why the constructor is not getting invoked.
Please tell me how to solve this.
public abstract class Preethi {
Preethi()
{
System.out.println("hirerew");
}
public static void main(String args[])
{
int a = 12;
if(a==0)
System.out.println("a");
if (a==12)
System.out.println("12");
}
}
You never create an instance of abstract class Preethi. Why do you expect the constructor to get called? Make a non-abstract subclass and create an instance of it and then the constructor will be called. main is static, it can be called without Preethi being realized.
public class X extends Preethi
{ /* Your implementation here */}
Then in main:
public static void main(String [] args)
{
Preethi preethi = new X(); // This will call the constructor of Preethi
}
Constructor is not being invoked because main() method is called without instantiating a main class.
To invoke it - you need to create an object of Preethi explicitly.
UPD. as anio suggests - you need to subclass Preethi and instantiate it.
Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time polymorphism is implemented through the use of superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be used to POINT TO A SUBCLASS object.
You can make it not abstract, or create a subclass that invokes super() on your abstract class.
See the code below:
public abstract class Preethi {
// constructor:
Preethi() {
System.out.println("hirerew");
}
public static void main(String[] args) {
// call the constructor:
new Preethi() {}; // "{}" needed because our class is abstract.
}
}
The point here is that you don't always have to create a new class, but can define a 'one-time' class next to the constructor. For example:
public abstract class A {
public abstract void foo();
public A() { foo(); }
}
You could do the following:
A a = new A() {
public void foo() {
System.out.println("hello");
}
};
The output would simply be "hello". A similar method could also be utilized for interfaces.
You are not creating object of Preethi. In order to make call to constructor, You have to remove abstract keyword from class and create it's object
Or create anonymous inner class and it's object as :
new Preethi() {
// abstract method impl
};
Or create sub class of Preethi, and create object of it.
FYI: You can create object references of any abstract class or interfaces. You can not create object of them.
And I think making main class abstract really does not make any sense. Atlease to me.(Tell me if I am wrong)