Q:

How to protect anonymous class creation with Interface reference

Consider the Business Scenario:
We have student Interface with payFees() method. There are some classes which implements student interface and implement payFees method. These are : SchoolStudent, CollegeStudent, UniversityStudent, OnlineStudent.
Now a developer will create the list of student as List<Student> and add different students to the list (SchoolStudent, CollegeStudent etc.).
Now developer can create anonymous class using Student interface, implements some faulty payFees method and add that object to the studentlist.
This anonymous student is not valid and it will distrub the business logic.
So how we will protect developer from creating anonymous class of Student interface.

A:

One way I can think of is (assuming all the valid implementations of Student interface are in the same package) to define a package private additional interface (let's call it ValidStudent) that the valid implementations implement in addition to implementing Student. That package private interface doesn't have to contain any methods.
Then, you can have some code that validates the Student instances added to the List - that validation code will check that those instances also implement the ValidStudent interface. Any custom implementations of Student won't pass that validation.
package x;
public interface Student
{
    ...
}

package x;
interface ValidStudent // package private
{
    // nothing here
}

package x;
public class SchoolStudent implements Student, ValidStudent
{

}

And an example for the validation (the validation can be done by any class in package x that does something with Student instances) :
package x;
public class StudentValidator
{
    public static boolean isValid (Student student) 
    {
        return student instanceof ValidStudent;
    }
}

