04 - Java Classes, Objects, Encapsulation
04 - Java Classes, Objects, Encapsulation
Encapsulation
IT Academy
Agenda
• Class and Object • Constructors
• Access to data • Creating objects
• Fields of class • Static Context
• Methods of class
• Encapsulation
Class and Object
• A class is a prototype (template) from which objects are created.
• An object is a software bundle of related state and behavior.
Student student1
has Last name - Petrenko
Last name First name - Ostap
First name Age - 19
Age List of courses – Java, MySQL
List of courses
student2
• Aside from the constructor, most methods can be grouped into two
types:
• accessor methods
• they return information to the user
• mutator methods
• they change the object's state (its fields)
Accessor Method
Mutator Method
Methods Overloading
• Object can have multiple methods with same name but different signature
(type and order of parameters).
class Person {
String name;
student.name = "Khrystyna";
student.age = 22;
Getters and Setters
• The following class uses private access control:
set
student.setName("Franko");
get
class Student {
private String name;
private int age;
private String[] courses;
stud2
Student stud2 = new Student("Olga");
stud2.setAge(24); Olga
count = 2
24
• You can invoke static method without any instance of the class to which it
belongs.
public class Runner {
public static void main (String[] args) {
Helper.setMessage("hello");
Helper.print();
// Not recommended:
Helper helper = new Helper();
helper.setMessage("new message");
helper.print();
}
}
Static Context
• A class can contain code in a static block that does not exist within a method body.
$ java Main
Hello Java!
Hello from method 'main'
• It's executed when the class is loaded and a good place to put initialization
of static variables.
Thanks for
attention!
IT Academy