Java Tutorial 4 Encapsulation

 Encapsulation

  • Encapsulation is the ability of an object to be a container (or capsule) for related properties (ie. data variables) and methods (ie. functions).
  • Encapsulation is one of three fundamental principles within object oriented programming languages.
  • The other two are inheritance and polymorphism
  • Data hiding is the ability of objects to shield variables from external access.
  • private variables can only be seen or modified by use of object accessor and mutator methods.
  • Access to other object variables can be allowed but with tight control on how it is done.
  • Methods can also be completely hidden from external use.

Class Specification

  • A class specifies the properties (data) and methods (actions) that objects can work with.

["public"] ["abstract""final"]"class" Class_name
["extends" object_name] ["implements" interface_name]
"{"
// properties declarations
// behavior declarations
"}"

  • The first optional group indicates the visibility or scope of accessibility from other objects.
  • public means visible everywhere.
  • The default (ie. omitted) is package (aka friendly) or visible within the current package only.
  • The second optional group indicates the capability of a class to be inherited or extended by other classes.
  • abstract classes must be extended and final classes can never be extended by inheritance.
  • The default (ie. omitted) indicates that the class may or may not be extended at the programmers discretion.
  • Class_name has initial letter capitalized by Java convention.

public class Box
{
// what are the properties or fields
private int length;
private int width;
private int height;
// what are the actions or methods
public void setLength(int p)
{length = p;}
public void setWidth(int p)
{width = p;}
public void setHeight(int p)
{height = p;}
public int displayVolume()
{System.out.println(length*width*height);}
}

Properties (aka Field Variables)

[ "public" "private" "protected" ] [ "final" ]
[ "static" "transient" "volatile" ]
data_type var_name [ = var_initializer ] ";"

  • Properties in Java are sometimes called field variables
  • The items in the first optional group indicate the 'visibility' or accessibility from other objects.
  • public means visible everywhere (global).
  • private indicates accessible only to this class and nested classes.
  • protected means visible to this class or inherited (ie. extended) classes only.
  • The default (keyword omitted) is friendly or visible within the current package (folder) only.
  • final indicates continuous retention and unchangeable after initial assignment (ie. it is read only or constant).
  • The third optional group indicates how long a value is retained in the variable.
  • static indicates that the value is shared by all members of the class and exists for all runtime. Static members can be referenced without creating an instance of the class.
  • transient prevents the variable from being transferred during a serial operation such as file i/o
  • volatile is used in threading to prevent overwrite issues.
  • The data_type is one of the primitive types listed in tutorial 2 and can be optionally initialized.
  • Many programmers choose to make all properties private and force access through accessors and mutators which can include validation steps.

Types of Methods

  • Class behaviour are represented in Java by methods.

[ "public" "private" "protected" ] [ "final" ]
[ "static" "abstract" "native" ]
return_data_type method_name "(" parameter_list ")"
"{"
// some defining actions
"}"

  • Accessibility keywords are the same as for properties. The default (ie. omitted) is package (aka friendly) or visible within the current package only.
  • static methods are shared and retained. abstract methods must be redefined on inheritance. native methods are written in C but accessible from Java.
  • The return_data_type defines the type of value that the calling routine receives from the object (the reply message in object terminology).
  • It can be any of the primitive types or the reserved word void (default value) if no message is to be returned.
  • The parameter_list can contain from zero to many entries of datatype variablename pairs. Entries are separated by commas.
  • Parameters are passed by value, thus upholding the encapsulation principle by not allowing unexpected changes or side effects.
  • Object references (such as arrays) can also be passed.

public static void example1() { }
public static int add2(int x) { x+=2; return x; }
public static double example3(int x, double d) { return x*d; }
public static void example4(int x, int y, boolean flagger) { }
public static void example5(int arr[]) { } // note: this is an object

  • Constructor methods allow class objects to be created with fields initialized to values as determined by the methods' parameters.
  • This allows objects to start with values appropriate to use

public Box() // default box is point
{length = 0; width = 0; height = 0;}
public Box(int l,int w,int h) // allows giving initial size
{length = l; width = w; height = h;}

  • there is no class keyword or return datatype keyword. Also the method name is the same as the class name. This is what marks the fragment as a constructor method.
  • a default constructor is automatically used to initialize all fields to 0, false or unicode(0) as appropriate to the datatype.
  • Constructors can be overloaded in the same way that instance methods are.
  • One clever programming device is to declare the constructor with no parameters as private and use it to initialize all properties. Then other constructors can first call it using this() and then do their own specific property validations/initialization.
  • Accessor (or observer) methods read property (ie field variable) values and are conventionally named getFoobar() or whatever the property is called.
  • Mutator (or transformer) methods set property values and are often named setFoobar() etc. Mutators can be used to ensure that the property's value is valid in both range and type.
  • Helper methods are those routines that are useful within the class methods but not outside the class. They can help in code modularization. Normally they are assigned private access to restrict use.

Overloading and Recursion

  • Overloaded methods are methods with the same name signature but either a different number of parameters or different types in the parameter list.
  • Recursive methods are methods that are defined in terms of themselves.

class Factorial{

int factorial(int n)

{ if (n==1) {return 1};

return (n * factorial(n-1)); }

}

Object Creation and Destruction

  • To create an object of a particular class use the creation method after the particular class has already been specified.

Box box_1 = new Box(3,4,5);

  • You do not need to destroy or remove an object when it is no longer needed. Java automatically flags unused objects and applies garbage collection when appropriate.
  • you may occasionally need to use the finalize method to insure that a non-Java resource such as a file handle or a window font character is released first.

void finalize(){

//cleanup code goes here

}

Inner Classes

  • Inner classes are classes nested inside another class. They have access to the outer class fields and methods even if marked as private.
  • Inner classes are used primarily for data structures, helper classes, and event handlers

public class Main2
{
class Person
{
// inner class defines the required structure
String first;
String last;
}
// outer class creates array of person objects with specific properties
// the objects can be referenced by personArray[1].last for example
Person personArray[] = {new Person(), new Person(), new Person()};
}

Project Organization

  • main() is normally a minimalist method, only instantiating worker model classes and perhaps doing command line analysis before passing control to an worker model method.
  • All methods should be short with a single function. Factor complex methods down to calls to simpler methods when possible.
  • It is good programming practice to write separate files for the class templates and the driver or main user program.

 

 

i wanna run away never say goodbey
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值