0

I am creating a simple drawing of a circle using Canvas and Paint.

I noticed that when I create the variable myPaint outside of init(), everything works perfectly fine; illustrated by the following code:

public class Drawing extends View {

    Paint myPaint;
    public Drawing(Context context) {
        super(context);
        init();
    }

    public void init(){
        myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        myPaint.setColor(Color.parseColor("yellow"));
    }


    @Override
    protected void onDraw(Canvas canvas) {

        canvas.drawCircle(getMeasuredWidth() /2, getMeasuredHeight() /2 , 100f, myPaint);
        super.onDraw(canvas);
    }
}

However, when I do the exact same thing, but instead create myPaint inside of init(), I get an error for myPaint in onDraw(); illustrated by the following code:

public class Drawing extends View {


public Drawing(Context context) {
    super(context);
    init();
}

public void init(){
    Paint myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    myPaint.setColor(Color.parseColor("yellow"));
}


@Override
protected void onDraw(Canvas canvas) {

    canvas.drawCircle(getMeasuredWidth() /2, getMeasuredHeight() /2 , 100f, myPaint);
    super.onDraw(canvas);
}
}

Why is this so? Thanks!

CodingChap
  • 1,088
  • 2
  • 10
  • 23

1 Answers1

0

In code B you're defining a local variable which is only accessible inside the code block it has been defined in (which is init method in this case). In contrast, code A defines a property which is accessible inside your object and leaves side by side of it.

You can also take a look at this.

Instance variables are declared in a class, but outside a method. When space is allocated for an object in the heap, a slot for each instance variable value is created. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.

Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.

Amin
  • 3,056
  • 4
  • 23
  • 34