lectures.alex.balgavy.eu

Lecture notes from university.
git clone git://git.alex.balgavy.eu/lectures.alex.balgavy.eu.git
Log | Files | Refs | Submodules

classes-and-instantiation.md (835B)


      1 +++
      2 title = 'Classes and instantiation'
      3 +++
      4 # Advanced Programming
      5 Classes have the form:
      6 
      7 ```java
      8 public class ClassName {
      9 }
     10 ```
     11 
     12 Instantiate classes with `new`:
     13 
     14 ```java
     15 ClassName instance = new ClassName();
     16 ```
     17 
     18 The name of the Java file should match the class name.
     19 One (main) class per file.
     20 
     21 Access variables via dot syntax: `car.brand`
     22 
     23 Instance variables are declared in the body of a class.
     24 `static` variables and methods are class variables/methods.
     25 
     26 Constructors are public, and have the same name as the class:
     27 
     28 ```java
     29 public class Main {
     30     int x;
     31 
     32     public Main() {
     33         x = 42;
     34     }
     35 
     36     public static void main(String[] args) {
     37         Main myMain = new Main();
     38         System.out.printf("The constructor sets the value: %d", myMain.x); // 42
     39     }
     40 }
     41 ```
     42 
     43 There are no destructors, as Java is garbage-collected.