Java FAQs
Posted on 01/04/2018Can we keep more than one class in a single java file?
Yes, it can. However, there can only be one public class per .java file, as public classes must have the same name as the source file. In general, there should be one class per file. If you organise things that way, then when you search for a class, you know you only need to search for the file with that name. The exception is when a class is best implemented using one or more small helper classes. Usually, the code is easiest to follow when those classes are present in the same file.
What are the differences between class variables and instance variables in Java?
They both are member variables, meaning that both are associated with a class. Now of course, there are differences between the two:
Instance variables:
These variables belong to the instance of a class, thus an object. And every instance of that class (object) has it’s own copy of that variable. Changes made to the variable don’t reflect in other instances of that class.
public class Product {
public int Barcode;
} Class variables:
These are also known as static member variables and there’s only one copy of that variable that is shared with all instances of that class. If changes are made to that variable, all other instances will see the effect of the changes.
public class Product {
public static int Barcode;
}