I was using previously this code:
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
and extended AppCompatActivity also but I was getting the same error. So in place of using Toolbar class, I have imported the below class and it worked for me:
android.support.v7.widget.Toolbar