Human: age, height, weight, eyeColor, etc.Dog: breed, numberOfLegs, etc.Car: brand, modelName, modelNumber, etc.Human: run(), walk(), eat(), talk()Dog: bark(), walk(), run(), sit()Car: startEngine(), accelerate(), brake()Syntax for fields and methods:
.value represents a field..add() represents a method.Fields are unique variables declared in a class and can be used by any methods in that class.
public class Foo {
int bar; // Field
Foo() {
// Constructor
this.bar = bar;
}
public static void someMethod() {
// Method
}
}
A field is different from a variable in that it is tied to a class.
Fields are initialized when they are declared.
int intField; // Initialized to 0
String strField; // Initialized to null
float floatField; // Initialized to 0.0f
static and are shared by all members of a class.In the scope of fields, we only deal with class variables and instance variables.
static keyword. These variables are shared across all instances of the class.Ex)
public class SomeClass {
public static int cnt = 0;
public static void increaseCnt(){
cnt++;
}
}
public class Example {
public static void main(String[] args){
SomeClass someClass1 = new SomeClass();
SomeClass someclass2 = new SomeClass();
someClass1.increaseCnt();
System.out.println(someClass1.cnt); // 1
System.out.println(someClass2.cnt); // 1
}
}
We can see that even though someClass2 didn't call increaseCnt() method, it still prints 1.
static keyword. Each instance (object) of the class has its own individual state.Ex)
public class SomeClass {
private String someField; // Instance variable
public SomeClass(String someField) {
this.someField = someField;
}
}
Each
SomeClassobject will have its own copy ofsomeField.
Ex)
public class SomeClass {
public void someMethod() {
int temp = 90; // Local variable
System.out.println("Temp Value: " + temp);
}
public void anotherMethod(){
System.out.println(temp); // Compiler Error!
}
}
temp is a local variable that only exists during the execution of the someMethod. Trying to access the temp variable in another method will cause a compiler error because it’s out of scope in that method.
(!) The Java file name must match the class name.
// Foo.java
public class Foo {
}
new OperatorUsed to create a new instance of a class.
ClassName objectName = new ClassName();
OR
ClassName objectName = null;
objectName = new ClassName();
A class is like a blueprint or template used to create an object (instance).
An instance is the actual object created from the class.
Car brandNewCar = new Car("brandName", "modelName", "licensePlateNumber");
The new operator creates a new object in the Heap Area of memory.