CS2312 Lecture 3

Object Encapsulation and References

Object-oriented languages are designed to facilitate structuring code at high levels of abstraction.
One of the key features of these languages is the ability to structure code at the level of classes.
In Java,
All(Almost) codes occurs in a method,  
all methods belong to a class
all classes belong to a package.
 
Classes are
  • collections of methods and fields
  • Types
data types:
  • int
  • float, double
  • byte, char
  • boolean
 
classes:
  • Integer
  • Float, Double
  • Byte, Char
  • Boolean
  • String

 

Visibility Modifiers

public - makes methods and data fields accessible by any other class

private - makes methods and data fields accessible only from within its own class

(neither) – similar to public but a bit more restricted

 
Accessors – get the value of a data field
Mutators – set the value of a data field
public class BankAccount{
    ....
    //accessors
    public double getBalance(){
        return balance;
    }
    public String getName(){
        return name;
    }

    //mutators
    public void deposit(double amount){
        ....
    }
    public void withdraw(double amount){
        ....
    }
}

 

Private method: Methods of a class that are declared private can only be called within the class.
 
 
•Accessibility modifiers are not used for safety
–There are ways around them in Java!
•They are used for encapsulation!
–Hide unnecessary state/methods from user of class
–Prevent access to state to maintain object consistency
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
posted @ 2018-02-09 14:31  Charonnnnn  阅读(141)  评论(0编辑  收藏  举报