0

Alright, I think this is a faily simple question, but I just can't wrap my head around this.

Lets say I have this pseudo classes with their respective functionalities. Can I call the methods from within the constructor itself, so it launches on object creation?

Class One

public class Apples{

    public String a;
    public String b;

    Apples(String a, String b){
        this.a = a;
        this.b = b;
        specificMethod();
    }

    public void randomMethod(){
        System.out.println(this.a)
    }

    public void specificMethod(){
        System.out.println(this.b)
    }

}

Class Two

public class Oranges{
    Apples green = new Apples(a,b)
}
Riley Carney
  • 804
  • 5
  • 18
zython
  • 1,176
  • 4
  • 22
  • 50
  • 1
    Have you tried it? Your specific method call is incorrect by the way, as it doesn't accept any arguments. But I don't believe that's what you're asking about – Joseph Young Jan 19 '16 at 20:45
  • specifiMethod != specificMethod - this should result in a compilation error. Also, I do not understand the question. What is it that you do not understand? What did you expect instead of what you see? – tucuxi Jan 19 '16 at 20:48
  • You can call methods of the same class from the constructor, but these methods should be either `final` or `private`, i.e. non-overridable. – Mick Mnemonic Jan 19 '16 at 20:58

2 Answers2

1

Yes, if you put a method in an object constructor which is called it will run the methods inside the constructor.

Riley Carney
  • 804
  • 5
  • 18
  • 1
    this should be a comment, not an answer – tucuxi Jan 19 '16 at 20:47
  • Ah, I see that you have just edited it. As it is currently phrased, it does not make much sense. I suggest changing "which is initialized" to "which is then called" – tucuxi Jan 19 '16 at 20:51
1

Yes. Many people will even just call an _init function instead of doing everything inside the constructor. That way you can reinitialize an object without creating a new one.

Sku Sku
  • 191
  • 1
  • 5
  • 2
    not many people that I know of would use underscores as part of java method names - `initialize()` would sound more javaish – tucuxi Jan 19 '16 at 20:46