Classes and Objects in Java
A class describes the state and behaviour of a kind of thing, and an object is one concrete instance of that description held in memory.
Classes, objects, inheritance, polymorphism and abstraction.
12 notes
A class describes the state and behaviour of a kind of thing, and an object is one concrete instance of that description held in memory.
A constructor runs once when an object is created, and its job is to leave that object in a valid state.
Inside an instance method, this is a reference to the object the method was called on, which resolves shadowing and enables chaining.
static binds a member to the class rather than to any instance, which changes when it is created, how it is accessed and what it can see.
Encapsulation hides internal state behind a deliberate public surface, so a class can guarantee its own rules stay true.
Four levels of visibility control who can see a member, and choosing the narrowest one that works is the single easiest design win.
Inheritance lets a subclass acquire the members of a superclass, creating an is-a relationship that polymorphism is built on.
A subclass replaces inherited behaviour by declaring the same signature, and the JVM chooses the version at runtime from the actual object.
One reference type, many possible behaviours. Polymorphism is what lets code work with a supertype and stay correct as new subtypes appear.
Abstraction exposes what a type does and hides how. Abstract classes share partial implementation, interfaces declare a capability.
Most relationships between classes are has-a, not is-a. Composition is usually the more flexible and more honest design.
From new to unreachable: how objects are created, how long they live, and what actually happens when nothing references them any more.