Create an Instance of an abstract class - java

package corejava;
abstract class abstractA // abstract class A
{
abstract void abst(); // Abstarct Method
void eat() // Non abstract method
{
System.out.println("non abstract");
}
}
class B extends abstractA // class B extends abstract Class
{
#Override // define body of abstract method
void abst() {
System.out.println("abstract method define");
}
void eat() // override eat method
{
System.out.println("non abstract override ");
}
}
public class alloops { // Main class
public static void main(String[] args)
{
B b=new B(); // create Object B Class
abstractA a = new abstractA() { // create Object of abstract Class
#Override
void abst() {
System.out.println("again abstract");
}
};
a.eat(); //instance of abstract class
System.out.println(a instanceof abstractA);
b.abst();
b.eat();
a.abst();
}
}
Output:
non abstracttrue,abstract method definenon abstract override again abstract
In this case output is above. I want to know if it's right or wrong. Do I have have to create an instance of the abstract class or not?

What you have done is creating an anonymous inner class.
abstractA a = new abstractA() { // create Object of abstract Class
#Override
void abst() {
System.out.println("again abstract");
}
};

abstractA a = new abstractA() {
#Override
void abst() {
System.out.println("again abstract");
}
};
The above code actually defined an anonymous class extending your abstract class. Your code works as it's expected.

You can't create an instance of abstract class.You are creating an instance of anonymous inner class which is extending your abstract class. Confusion is creating because this line
is returning true.
a instanceof abstractA
instanceof is used to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
In this case abstractA is an instace of abstract class's
subclass.
Output will be more clear if you use these lines to determine class types of instances
System.out.println(b.getClass().toString());
System.out.println(a.getClass().toString());
Output:
class corejava.B
class corejava.alloops$1
First line of the output tells that
b
is an instance of class B in package corejava
Second line tells that a is the first anonymous inner class ($1) of class alloops of package corejava

Related

Why can I instantiate objects of abstract classes and interface? What is the super in constructor?

Here I instantiate objects from two abstract classes and an interface. I wonder why I can do that in three cases, especially the case of NotShape class where there is no abstract method. And the second question is that, What is the "super" when I instantiate the object of NotShape class? Is it belong to Object class or NotShape class itself? I thank you so much.
abstract class Shape{
String descrOfShape = "This is a shape";
abstract void draw();
}
abstract class NotShape {
String descrOfNotShape = "This is not a shape";
void printInfo() {
System.out.println("Can't be measured");
}
}
interface Test{
int ID = 10;
void showResult();
}
public class InstantiateObjects {
public static void main(String[] args) {
Shape s = new Shape() {
#Override
void draw() {
}
};
NotShape ns = new NotShape() {
#Override
void printInfo() {
super.printInfo(); /*What is the super? Is it belong to Object
class or NotShape class?*/
}
};
Test t = new Test() {
#Override
public void showResult() {
}
};
System.out.println(s.descrOfShape);
System.out.println(ns.descrOfNotShape);
System.out.println(t.ID);
}
}
You're not instantiating an abstract class or interface, you're instantiating a private anonymous extension/implementation of the abstract class/interface.
More reading: https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
Here You implementing interface or abstract class on your main method. You can not instantiate abstract class or interface never. But you can inherit then from another class or interface(depends on inheritance rules). Here you are instantiate a anonymus class which means you are implementing your interface or extending your abstruct classes. And your
#Override
void draw() {
}
and
#Override
void printInfo() {
super.printInfo(); /*What is the super? Ans: super means its call its parent class. Is it belong to Object class or NotShape class? Ans: Obviously its belongs to parent class NotShape*/
}
They are obviously overiding super classes(interfaces and abstruct classes) methods. You can try this then you can see its overiding your printinfo method
NotShape ns = new NotShape() {
#Override
void printInfo() {
super.printInfo(); /*What is the super? Is it belong to Object
class or NotShape class?*/
}
};
ns.printInfo();
That means you are calling your anonymus classes method. and then its calling your super classes because you are calling super.printInfo();
NB: take further study on highlighted terms. Thanks.

creating Abstract class object java

public abstract class AbstractObject {
AbstractObject(){
System.out.println("mahi2");
}
}
class PrintMahi extends AbstractObject{
public static void main(String ... args){
PrintMahi m = new PrintMahi();
}
}
In above code I understand that the PrintMahi object is getting created and because of inheritance superclass which is abstract in this case constructor is getting called. So is it like that the abstract class object is being created here?

calling non abstract method in abstract class java

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

Abstract class in Java.

Wat does it mean by indirect Instantiation of abstract class ? how do
we achieve this ?
as i tried few times like .. it gives error has any one done something regarding this
abstract class hello //abstract class declaration
{
void leo() {}
}
abstract class test {} //2'nd abstract class
class dudu { //main class
public static void main(String args[])
{
hello d = new test() ; // tried here
}
}
We can't instantiate an abstract class .If we want than we have to extend it.
You can't instantiate an abstract class. The whole idea of Abstract class is to declare something which is common among subclasses and then extend it.
public abstract class Human {
// This class can't be instantiated, there can't be an object called Human
}
public Male extends Human {
// This class can be instantiated, getting common features through extension from Human class
}
public Female extends Human {
// This class can be instantiated, getting common features through extension from Human class
}
For more: http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
Wat does it mean my indirect instanciation of abstract class ? how do we achieve this ?
I'd need to see the context in which that phrase is used, but I expect that "indirect instantiation" means instantiation of a non-abstract class that extends your abstract class.
For example
public abstract class A {
private int a;
public A(int a) {
this.a = a;
}
...
}
public B extends A {
public B() {
super(42);
}
...
}
B b = new B(); // This is an indirect instantiation of A
// (sort of ....)
A a = new A(99); // This is a compilation error. You cannot
// instantiate an abstract class directly.
You can't create instance of abstract class, I think this is what you are trying to do.
abstract class hello //abstract class declaration
{
void leo() {}
}
class test extends hello
{
void leo() {} // Custom test's implementation of leo method
}
you cannot create object for Abstract class in java.
Refer this link-http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

If a child class extend Base class Exception

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);
...
}

Categories

Resources