0% found this document useful (0 votes)
55 views39 pages

Class Design, Encapsulation

The document provides an overview of class design and encapsulation in Java, detailing the structure of classes, methods, and constructors. It emphasizes the importance of encapsulation for data protection and outlines the roles of access specifiers, getters, and setters. Additionally, it discusses static context, reference types, and the significance of a well-defined interface for class usability.

Uploaded by

eramchegyt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views39 pages

Class Design, Encapsulation

The document provides an overview of class design and encapsulation in Java, detailing the structure of classes, methods, and constructors. It emphasizes the importance of encapsulation for data protection and outlines the roles of access specifiers, getters, and setters. Additionally, it discusses static context, reference types, and the significance of a well-defined interface for class usability.

Uploaded by

eramchegyt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Class design,

Encapsulatio
n
IT Academy
Agenda

• Class and Object • Static Context


• Access to data • Reference Types
• Fields of class • Encapsulation
• Methods of class
• Constructors
• Creating objects
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,
List of courses MySQL
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


-922372036854775808 < x <
long 64 0L
922372036854775807
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);
}
}

• 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;
}
}
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
public class Student {
private String name;
private int age;
public static int count = 0;
They
public Student(){ count++; } have the
public Student(String name){ same
this.name = name; name
count++;
}

public Student(String name, int age){


this.name = name;
this.age = age;
count++;
}
... getters, setters and methods
}
Creating Objects
stud
Student stud1 = new Student(); 1Dmytro
count = 1
stud1.setName("Dmytro"); 25
stud1.setAge(25);

stud
Student stud2 = new Student("Olga");
stud2.setAge(24);
2Olga
count = 2
24

Student stud3 = new Student("Ivan", 26);


stud
int number = Student.count; 3Ivan
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.
Reference Types

• A Reference is a data element that holds the address of a memory


location.
• A Reference Variable contains a “pointer” to an object.
Reference Types

• This statement has three parts:


• Declaring a Variable to refer to an Object;
• Instantiating a Class using new operator;
• Initializing an Object using the Constructor.
Objects and Assignment Operator
public class Main {
public static void main(String[] args) {
Rectangle rect1 = new Rectangle(30, 10);
Rectangle rect2 = new Rectangle(25, 15);

double result = rect1.getPerimeter();


boolean var = true;
}
}
Objects and Assignment Operator
public class Main {
public static void main(String[] args) {
Rectangle rect1 = new Rectangle(30, 10);
Rectangle rect2 = rect1;

double result = rect1.getPerimeter();


boolean var = true;
}
}
Passing Arguments to Method
public class Main {
public static void main(String[] args) {
int width = 25, height = 10;

System.out.println("width = " + width + "\theight = " + height);


swap(width, height);
System.out.println("width = " + width + "\theight = " + height);
}

public static void swap(int w, int h) {


int temp = w;
w = h;
h = temp;
System.out.println("width = " + w + "\theight = " + h);
}
}

Before calling method 'swap': width = 25, height = 10


Inside the method 'swap': width = 10, height = 25
After calling method 'swap': width = 25, height = 10
Passing Arguments to Method

swap
w 10
h 25
temp 25

main
width 25
height 10

Stack Memory Heap Memory


Passing Arguments to Method
• All object references in Java are passed by value.
• This means that a copy of the value will be passed to a method.

• Unfortunately, when we pass the object, we are passing the


copy of reference to it.
Passing Arguments to Method
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(25, 10);

System.out.println("Before calling method 'swap': width = " +


rectangle.width + ", height = " + rectangle.height);
swap(rectangle);
System.out.println("After calling method 'swap': width = " +
rectangle.width + ", height = " + rectangle.height);
}

public static void swap(Rectangle rect) {


int temp = rect.width;
rect.width = rect.height;
rect.height = temp;
System.out.println("Inside the method 'swap': width = " +
rect.width + ", height = " + rect.height);
}
}

Before calling method 'swap': width = 25, height = 10


Inside the method 'swap': width = 10, height = 25
After calling method 'swap': width = 10, height = 25
Passing Arguments to Method

swap
temp 25 Rectangle
Date
rect ref width 10 Wed Dec 15
height 25 11:26:43
main crtDate ref
rectangle ref

Stack Memory
Heap Memory
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).
A Class Involves at least 2 People
• The implementor wants to make a class that is easy to use.
• A user does not care how a class is implemented. He only wants
to know the operations that it can carry out (its interface).

• This interface helps the implementor decide on the class's


operation/methods.
Understanding Stack Object

• What does the user need to understand in order to use a Stack


object?
• User only needs to understand the interface.

• The user does not need to know how class is implemented.


Structure of Stack Class
public class Stack {
private int store[];
private int top;

public void push(int item) {


// some implementation
}

public int pop() { // some implementation }

public boolean isEmpty() { // some implementation }

public int size() { // some implementation }


}
BadStack Class interface
public class BadStack {
private int store[];

public int top;

public int pop() {


if (top == -1) throw new RuntimeException();
else {
int elem = store[top];
top--;
return elem;
} public static void main(String[] args) {
} BadStack stack = new BadStack(10);
} stack.push(42);
stack.push(17);
stack.top = 0;
stack.pop();
System.out.println("Size of Stack: " +

stk1.size());
}
Understanding the BadStack Object
• What does the user need to understand in order to use the BadStack
object?
• He needs to understand the interface and implementation.

• A good interface hides the class's implementation and a good interface


has easy-to-understand public methods.
Thanks for
attention!
IT Academy

You might also like