Classes, Objects,
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
can Last name - Romaniv
Pass an exam First name - Maryna
Enroll to course Age - 21
List of courses – .NET, MSSQL
Structure of Java Class
<access specifier> class ClassName {
// fields
<access specifier> data_type variable1;
...
<access specifier> data_type variableN;
// constructors
<access specifier> ClassName(parameter_list1) { method body }
...
<access specifier> ClassName(parameter_listN) { method body }
// methods
<access specifier> return_type method1(parameter_list) { method body }
...
<access specifier> return_type methodN(parameter_list) { method body }
}
Example of Java Class
public class Student {
private String lastName; fields
private String firstName;
private int age;
private Student(){} constructor
public boolean passExam(String subject){
//do something
return true;
}
public void print(){
//do something
} methods
}
Special Requirements to source files
• A source code file (.java) can have only one public class.
• Name of this class should be exactly the same of file name before extension
(including casing).
• Source code file can have any number of non-public classes.
• Most code conventions require use only one top-level class per file.
Default Values for Fields
Type Bits Value Default value
byte 8 -128 < x < 127 0
short 16 -32768 < x < 32767 0
int 32 -2147483648 < x < 2147483647 0
long 64 -922372036854775808 < x < 922372036854775807 0L
char 16 0 < x < 65536 '\u0000'
float 32 3,4e-38 < |x| < 3,4e38; 7-8 digits 0.0f
double 64 1,7e-308 < |x| < 1,7e308; 17 digits 0.0d
boolean 8 false, true false
String variable Symbols sequence of Unicode characters. null
Object variable Any object null
Methods
• Methods are functions that are executed in context of object.
• Always have full access to data of object.
• Method definition consists of a method header and a method body.
Kinds of Methods
• 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;
public void print() {
System.out.println(name);
}
public void print(String s) {
System.out.println(s + " " + name + "!");
}
public void print(int a) {
System.out.println(name + " is " + a + " years old" );
}
}
• Signature doesn't include return type, methods can't be
overloaded by return types.
Variable length Arguments
• Methods in Java support arguments of variable length.
• Should be last argument in method definition.
public class Util {
public static void print(String str, String... args) {
System.out.print(str);
for (String arg: args) {
System.out.print(arg);
}
}
}
public class Runner {
public static void main (String[] args) {
Util.print("Any ", arguments ", "are ", "possible", "!");
}
}
Access to Fields
• The following class uses public access control:
public class Student {
public String name;
public int age;
... Do not make so!
}
Student student = new Student();
student.name = "Khrystyna";
student.age = 22;
Getters and Setters
• The following class uses private access control:
public class Student {
private String name;
private Date date = new Date();
public String getName() {
return name;
}
public void setName(String value) {
name = value;
}
public Date getDate() {
return date;
}
}
Encapsulation
• Encapsulation in Java is a mechanism of wrapping the data (variables) and
code acting on the data (methods) together as a single unit.
• Encapsulation is used to hide the values or state of a structured data object
inside a class, preventing unauthorized parties direct access to them.
• Benefits of Encapsulation:
• the fields of a class can be made read-only or write-only;
• a class can have total control over what is stored in its fields;
• Isolation your public interface from change (allowing your public interface to stay
constant while the implementation changes without affecting existing consumers).
Getters and Setters
Student student = new Student();
set
student.setName("Franko");
get
String studentName = student.getName();
Keyword this
• The keyword this always points to current object.
• Often needed to distinguish between parameters and fields:
public class Student {
private int age;
public void setAge(int age) {
this.age = age;
}
}
Constructors
• Constructors – special kind of methods called when instance created.
• Class may have multiple overloaded constructors.
• If not provided any constructor, Java provides default constructor.
public class Student {
private String name;
private int age;
public Student(String name) {
this.name = name;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Constructors and keyword this
• Constructors in the same class can call another constructor with the keyword
this and the parameters list.
• Doing so is called an explicit constructor invocation.
class Student {
private String name;
private int age;
private String[] courses;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student(String name, int age, String[] courses) {
this(name, age);
this.courses = courses;
}
}
Constructors
public class Student {
private String name;
private int age;
public static int count = 0;
public Student(){ count++; }
They have
the same
public Student(String name){
this.name = name;
name
count++;
}
public Student(String name, int age){
this.name = name;
this.age = age;
count++;
}
... getters, setters and methods
}
Creating Objects
stud1
Student stud1 = new Student(); Dmytro
count = 1
stud1.setName("Dmytro"); 25
stud1.setAge(25);
stud2
Student stud2 = new Student("Olga");
stud2.setAge(24); Olga
count = 2
24
Student stud3 = new Student("Ivan", 26);
stud3
int number = Student.count; Ivan
count = 3
26
System.out.println(number);
Static Context
• Keyword static indicates that some class member (method or field) is not
associated with any particular object.
• Static members should be accessible by class name (good practice, not required
by language itself).
public class Helper {
private static String message;
public static void setMessage(String message) {
Helper.message = message;
}
public static void print() {
System.out.println(message);
}
}
Static Context
• 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.
public class Main {
static String str = "Hello Java!";
static {
System.out.println(str);
}
public static void main(String[] args) {
System.out.println("Hello from the method 'main'");
}
}
$ 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