Java: Abstract Class Invocation via Main Method - java

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.

Related

Abstract class 'instantiation' with a body of its methods

I am starting java programming and I came across abstract classes. I know that you cannot instantiate them without creating concrete classes which extend them to become the subclass. However, I got really confused when I tried this code and it runs ok.
abstract class Communication{
public void FirstMethod()
{
System.out.println("I am first method()\n");
}
}
public class Main{
public static void main(String[] args){
Communication communication = new Communication() {
#Override
public void FirstMethod(){
super.FirstMethod();
}
};
communication.FisrtMethod();
}
}
Output is: I am first method().
If I modify it to:
Communication communication = new Communication() {
#Override
public void FirstMethod(){
System.out.println("I've been called from Main");
}
};
The output is: I've been called from Main.
Could somebody please explain if this is a kind of instantiation or what concept is this?
This is termed as
Anonymous Class
Definition:
An inner class declared without a class name is known as an anonymous inner class.
In case of anonymous inner classes, we declare and instantiate them at the same time. Generally, they are used whenever you need to override the method of a class or an interface.
This is called anonymous inner class. This way you can implement an interface or abstract class without having to find a name for it and instantiate it at the same time. This concept is useful when you use a certain implementation just once.
The construct looks always like that:
new SomeClass() {
//implementation of methods
};
This is known as anonymous class. The anonymous class definition allows you to provide a class definition within code and it has no formal name. The anonymous class expression has the class definition and instance creation expression.This is not limited to abstract classes but also for interfaces and concrete classes.
For example
abstract class A { }
// so the anonymous class expression is
A a = new A() {// class definition };
// This will actually create an instance of a
// class that extends the abstract class A
// that java will create at run time
You can even use anonymous class expression in the method arguments.Example of this is a Comparator in Collections.sort() method;
Collections.sort(listOfValues,new Comparator<Value>(){
public int compare(Value v1, Value v2){
// method implemetation.
}
})

Abstract class having a main?

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.

What is the use of main method in abstract class?

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.

Can we use static method in an abstract class?

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.

This appears to create an object from an interface; how does it work?

interface Int {
public void show();
}
Int t1 = new Int() {
public void show() {
System.out.println("message");
}
to.show();
You're defining an anonymous class that implements the interface Int, and immediately creating an object of type thatAnonymousClassYouJustMade.
This notation is shorthand for
Int t1 = new MyIntClass();
// Plus this class declaration added to class Test
private static class MyIntClass implements Int
public void show() {
System.out.println("message");
}
}
So in the end you're creating an instance of a concrete class, whose behavior you defined inline.
You can do this with abstract classes too, by providing implementations for all the abstract methods inline.
What this special syntax for anonymous inner classes does under the hood is create a class called Test$1. You can find that class file in your class folder next to the Test class, and if you printed t1.getClass().getName() you could also see that.
i think your object has nothing to do with the interface. If you comment out the whole interface, still you will get the same output. Its just anonymous class created. I think, unless you use the class "implements" you cant implement the interface. But i dunno how naming collision doesn't happen in your case.

Categories

Resources