fields of an object are data variables. Also, referred to as attributes or
member variables.
usually made up of primitive types like integers or characters, but can also
be objects themselves.
-
Access fields
String title; String author; int numberOfPages; // String myBookTitle = book.title; System.out.println(book.title);
-
Setting fields
book.numberOfPages = 234;
Methods
Run actions in objects looks like calling a function.
Calling a method
void setBookmark(int pageNumber);
Points on Classes
- Classes is a blueprint of what the object should look like
- Object is the actual entity created from that Class
- Classes have all the fields and implements all the methods
- Classes and Objects are two different words
Table - Class
vs Object
Class | Object | |
---|---|---|
What: | A Data Type | A Variable |
Where: | Has its own file | Scattered around the project |
Why: | Defines the structure | Used to implement to logic |
Naming convention: | CamelCase (starts with an upper case) | camelCase (starts with a lower case) |
Examples: | Country | australia |
Table - Java classes around primitive types
Class | Primitive type |
---|---|
Integer | int |
Long | long |
Double | double |
Character | char |
String | char[] |
code example - Pokemon Class
class Pokemon {
String name;
String type;
int health;
boolean dodge() {
return Math.random() > 0.5;
}
void attack(Pokemon enemy) {
if(!enemy.dodge()) {
enemy.health--;
}
}
}
What each term in main() method definition means?
public static void main(String[] args) {
}
-
public
- Run this method from anywhere in Java program -
static
- Does not need an object to run -
void
- Main method doesn't return any output. It invokes the logic inside themain
method -
main
- name of the method -
String [] args
- Input parameter (array of strings)
Java program won't run if the main
method is not available or if defined more than once.
Self reference:
- To refer an object within one of its methods or constructors, use keyword
this
. -
this
is a reference to the current object - the object whose method or constructor is being called.
class Size { int rows = 0; int columns = 0; // // constructor Size(int rows, int columns) { this.rows = rows; this.columns = columns; } }
With
this.rows
we are referring tofield
rows
not the input parameter.https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
An example implemented here: https://github.com/j143/untitled-java
Private vs public access
- Use getters and setters if the public access required for a field
- Declare all fields as private where possible
-
package public
is the default. It will labelpublic
only in the same package/folder. - Set helper methods to
private
- Set action methods to
public
Top comments (0)