Classes and Objects in Java

In Java, everything is in a class. Java is strongly object oriented — unlike C which has no objects or Javascript where objects are optional.

Java source files are named the same as the class they define, with an extension of .java

public class MyClass

STATIC variables and STATIC functions

  • Static things exist at the class level. There is only one copy of these.
  • They are made automatically when the program compiles.
  • Static functions cannot access anything that is not static. This is because instance variables and instance methods exist in individual objects. But there may be many multiple different copies of these if you have created many objects.

more on Static


  • A constructor is used to make the object.
  • A constructor has no return value.
  • There is normally more than one constructor in a class

more on Constructors

INSTANCE variables and functions

  • These variables and methods are only made when you make an object.
  • The class file acts as a template or blueprint.
    The instance variables and methods are copied from the class template and put into an object and intialized according to the constructor(s).
  • Instance methods can access static variables and methods, but not vice versa.
  • There is no "prefix" for Instance variables and methods. You don't write "instance int number;"

more on Instance and Objects


Java classes can also have classes inside them. ... more later ...


Accessing Variables

You cannot have a static variable and an instance variable with the same name

class MyClass{

   static int v1 = 5;
   int v2 = 6;

   void someMethod() {
      int v1 = 17, v2 = 18; //local variables
      this.v2 = 19; 	//instance variable
      MyClass.v1 = 20 	//static variable