user8000188
user8000188

Reputation: 1

How to call a method from another class?

public class ClassOut {

    abstract class ClassIn {

        int x = 20;

        public void print() {
            System.out.println("value = " + getX());
        }

        public abstract int getX();
    }
}

How to call method print() from another class ?

Upvotes: 0

Views: 341

Answers (3)

vijayraj34
vijayraj34

Reputation: 2415

Instantiation of abstract class is not possible you have to subclass it in order to use its non static fields and methods.

new ClassOut().new ClassIn(){
    public int getX() {
         return 1; 
    }
}.print();

Here I've done the anonymous implementation​ of the inner abstract class in order to create the instance of it and call the instance method.

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44854

If the abstract was a standalone class (not inner) then you could simply extend it

public class MineClass extends Classin {

   // implement getX
}

then you can call it as

new MineClass().print();

Upvotes: 1

luanlucas
luanlucas

Reputation: 29

It's quite simple. As you have an abstract class you'll need a concrete class to extends it, doing that you can @override the method print() in your subclass, for example:

class ClassInChild extends ClassIn {
    @override
    public void print() {
        System.out.println("new value = " + getX());
    }

    // mandatory because it is abstract
    @override
    public int getX() {
        return 5;
    }
 }

 ClassIn classIn = new ClassInChild();
 classIn.print();

If it all goes right, you should receive new value = 5 as response.

Upvotes: 0

Related Questions