0

I have some strange question.

I want to make constructor in java output some statements without using System.out inside the constructor itself.

This is my code:

public class NewClass1 {

public int view()
{
return 6;
}

public NewClass1()
{
    int a = view();
    System.out.println(a);
}

public static void main(String argv[])
{
    NewClass1 object = new NewClass1();
}

}

Now when i create object form that class it will output(6).

My question is: output 6 once the object is created but without using any outputs statements?

Beginner Programmer
  • 155
  • 1
  • 4
  • 16

1 Answers1

1

You could create a class that handles only printing what you feed it like so

public class ConstructorPrinter {

    public void print(int a) {
        System.out.println(a);
    }
}

And then in your NewClass1 class you could use it in the following way

public class NewClass1 {
    ConstructorPrinter constructorPrinter = new ConstructorPrinter();

    public int view()
    {
        return 6;
    }

    public NewClass1()
    {
        constructorPrinter.print(view());
    }

    public static void main(String argv[])
    {
        NewClass1 object = new NewClass1();
    }
}
Brandon Laidig
  • 430
  • 2
  • 14
  • no, this is not my question. my question is that i want to output a value without using System.out inside the class or constructor. – Beginner Programmer Nov 05 '15 at 22:35
  • @BeginnerProgrammer if you want to output something while you are in the constructor, you need to use `println(...)` within the constructor (at least if you want your code to stay somewhat simple). – Turing85 Nov 05 '15 at 22:40
  • @BeginnerProgrammer would an entirely new class that just prints whatever you feed it be what you're looking for then? If so, I can help you out with that – Brandon Laidig Nov 05 '15 at 22:41
  • @BrandonLaidig not exactly what i am looking for but anyway post your answer to see :) – Beginner Programmer Nov 05 '15 at 22:51
  • @BeginnerProgrammer I've updated my answer. Let me know – Brandon Laidig Nov 05 '15 at 22:56
  • it's a good answer and +1 to it ... but if i tell you that i don't need to use any output statements inside any classes or constructors, is this possible? if impossible then your answer is the best one. – Beginner Programmer Nov 05 '15 at 23:04
  • 2
    @BeginnerProgrammer to the best of my knowledge, it's not possible to output without using an output – Brandon Laidig Nov 05 '15 at 23:06
  • 1
    If you want to output something, at some point it has to go past output. You can put a lot of stuff in between, but is is like getting to an other country; it does not matter how long you make the road, or how weird the way you take is, at one point you will have to cross the border. – Flummox - don't be evil SE Nov 05 '15 at 23:11