comp1004 building better objects ii n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Comp1004: Building Better Objects II PowerPoint Presentation
Download Presentation
Comp1004: Building Better Objects II

Loading in 2 Seconds...

play fullscreen
1 / 32

Comp1004: Building Better Objects II - PowerPoint PPT Presentation


  • 107 Views
  • Uploaded on

Comp1004: Building Better Objects II. Encapsulation and Constructors. Coming up. Recap Variables, Scope and Methods Accessor Methods Getters and Setters Encapsulation public and protected Constructors. Recap. Scope. public class Account{ int balance = 100;

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

Comp1004: Building Better Objects II


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
comp1004 building better objects ii

Comp1004: Building Better Objects II

Encapsulation and Constructors

coming up
Coming up
  • Recap
    • Variables, Scope and Methods
  • AccessorMethods
    • Getters and Setters
  • Encapsulation
    • public and protected
  • Constructors
scope
Scope

public class Account{

int balance = 100;

public void withdrawFiver(){

balance = balance -5;

}

public void withdrawTenner(){

int tenner = 10;

balance = balance – tenner;

}

}

Member variables are visible in all the methods of a class.

They are created when an object is created, and destroyed when the object is garbage collected

scope1
Scope

public class Account{

int balance = 100;

public void withdrawFiver(){

balance = balance -5;

}

public void withdrawTenner(){

int tenner = 10;

balance = balance – tenner;

}

}

Member variables are visible in all the methods of a class.

They are created when an object is created, and destroyed when the object is garbage collected

Local variables are only visible in the method in which they are declared.

They are created when the method is invoked, and destroyed when it ends.

primitives vs references
Primitives vs. References

b

a

int a;

a = 10;

Elephant b;

b = new Elephant();

Elephant

int

10

methods and parameters
Methods and Parameters

public class Account{

int balance = 100;

public static void main(String[] args){

Account myAccountObject = new Account();

myAccountObject.withdraw(5);

myAccountObject.withdraw(10);

}

public void withdraw(int amount){

balance = balance - amount;

}

}

Values passed into a method are called arguments

Values received by a method are called parameters.

Within the method they can be used like any other local variable

methods and parameters1
Methods and Parameters

public class Account{

int balance = 100;

int overdraft = 100;

public static void main(String[] args){

Account myAccountObject = new Account();

myAccountObject.withdraw(5);

int funds = getAvailableFunds();

System.out.println(funds);

}

public void withdraw(int amount){

balance = balance - amount;

}

public intgetAvailableFunds(){

return balance + overdraft;

}

}

You can use a return type to return a single value from a method

overloading
Overloading

public class Account{

int balance = 100;

public static void main(String[] args){

Account myAccountObject = new Account();

myAccountObject.withdraw(5);

myAccountObject.withdraw(10);

}

public void withdraw(int amount){

balance = balance - amount;

}

public void withdraw(int amount, String desc){

balance = balance - amount;

System.out.print(“Withdrew £”);

System.out.print(amount);

System.out.print(“ via ”);

System.out.println(desc);

}

}

Methods can take multiple parameters

Several Methods can have the same name as long as their signatures (types and order of parameters) are different.

getters and setters
Getters and Setters
  • Programming convention
  • Puts a method between users of an object and the data inside the object

int a = student.age;

int a = student.getAge();

student.age = 20;

student.setAge(20);

slide12
aka
  • These are also known as Getters and Setters
    • Or more formally as Accessorsand Mutators.
  • You’ll find them a lot
  • The library classes that Java provides follow this convention often.
but why do it
But Why Do It?
  • What reason is there to write this extra code, when you can use the class variables directly?

public intgetAge(){

return age;

}

encapsulation
Encapsulation
  • This is the idea that a class should be responsible for managing itself
  • And should present a clean interface (set of methods) to the outside world
  • An interface that does not reveal the inner workings of the class
encapsulation1
Encapsulation
  • This is the idea that a class should be responsible for managing itself
  • And should present a clean interface (set of methods) to the outside world
  • An interface that does not reveal the inner workings of the class

This means that you can change the way that the class works, without changing any other parts of the program

Results in cleaner, more portable code, that is more maintainable and reusable.

for example
For example

Take this example class where age is modelled as an int

public class Student {

int age = 20;

//code omitted

public static void main(String[] args){

Student s1 = new Student();

System.out.println(s1.getAge());

}

public intgetAge(){

return age;

}

}

for example1
For example

Take this example class where age is modelled as an int

public class Student {

//intage = 20;

Calendar dateOfBirth;

//code omitted

public static void main(String[] args){

Student s1 = new Student();

System.out.println(s1.getAge());

}

//public intgetAge(){

// return age;

//}

public intgetAge(){

Calendar rightNow = Calendar.getInstance();

int a = calculateAge(rightNow, dateofBirth);

return a;

}

}

We might change the way that age is implemented – e.g. to make it based on the current date.

Because we used an Accessor we do not need to alter main

enforcing good behaviour
Enforcing Good Behaviour
  • So we have used methods to hide the way that our class is implemented
  • But what happens if we forgot and accidently access the variable directly?
  • Or if someone else uses our class in their program and ignores the accessor methods?
protected
Protected

The protected keyword tells Java that only methods in this class* can access this variable.

*and its sub-classes, but we’ll come to that later in the course…

public class Student {

//intage = 20;

protected Calendar dateOfBirth;

//code omitted

public static void main(String[] args){

Student s1 = new Student();

System.out.println(s1.getAge());

}

//public intgetAge(){

// return age;

//}

public intgetAge(){

Calendar rightNow = Calendar.getInstance();

int a = calculateAge(rightNow, dateofBirth);

return a;

}

}

protected1
Protected

The protected keyword tells Java that only methods in this class* can access this variable.

*and its sub-classes, but we’ll come to that later in the course…

public class Student {

//intage = 20;

protected Calendar dateOfBirth;

//code omitted

publicstatic void main(String[] args){

Student s1 = new Student();

System.out.println(s1.getAge());

}

//public intgetAge(){

// return age;

//}

publicintgetAge(){

Calendar rightNow = Calendar.getInstance();

int a = calculateAge(rightNow, dateofBirth);

return a;

}

}

And yes, public means the opposite – that all other methods can access it!

encapsulation2
Encapsulation
  • The idea that classes look after themselves and hide their internal workings
  • Is a key concept in Object Oriented Programming
  • And is enforced using the public or protectedkeywords*
  • Which can be applied to both member variables and methods

*There is also a private keyword (we come to that later too)

a hint
A Hint
  • Good OO programmers are paranoid
  • If you want to make good encapsulated classes treat everything as protected
  • Only open up methods or member variables as public if you really want them to be accessed outside of the class.
back at our simple student e xample
Back at our simple Student Example

We have a problem – all our students will be age 20

public class Student {

protected int age = 20;

//code omitted

public static void main(String[] args){

Student s1 = new Student();

System.out.println(s1.getAge());

}

public intgetAge(){

return age;

}

}

back at our simple student e xample1
Back at our simple Student Example

We have a problem – all our students will be age 20

public class Student {

protected int age = 20;

//code omitted

public static void main(String[] args){

Student s1 = new Student();

s1.setAge(19);

System.out.println(s1.getAge());

}

public intgetAge(){

return age;

}

public void setAge(int a){

age = a;

}

}

One solution is to use a Setter method. But Is this good encapsulation?

back at our simple student e xample2
Back at our simple Student Example

We have a problem – all our students will be age 20

public class Student {

protected int age = 20;

//code omitted

public static void main(String[] args){

Student s1 = new Student();

s1.setAge(19);

System.out.println(s1.getAge());

}

public intgetAge(){

return age;

}

public void setAge(int a){

age = a;

}

}

One solution is to use a Setter method. But Is this good encapsulation?

No – object creation is in two steps. Someone could forget to set it before using the object.

We need a way to force a program to set the age at the point of object creation

constructors1
Constructors
  • Look a bit like methods
  • Contain code that is called during the creation of objects
  • Is used to initialise objects and set critical member variables
  • This maintains Encapsulation
constructors2
Constructors

public class Student {

protected age;

public Student() {

age = 20;

}

//code omitted

}

Constructor Rules:

  • Must have the same name as the class
  • Do not need a return type
constructors3
Constructors

public class Student {

protected age;

public Student() {

age = 20;

}

public Student(int a) {

age = a;

}

//code omitted

}

Constructor Rules:

  • Must have the same name as the class
  • Does not need a return type
  • Can take parameters
  • Can be overloaded
constructors4
Constructors

public class Student {

protected age;

public Student() {

age = 20;

}

public Student(int a) {

age = a;

}

public static void main(String[] args){

Student s1 = new Student(19);

System.out.println(s1.getAge());

}

//code omitted

}

Constructor Rules:

  • Must have the same name as the class
  • Does not need a return type
  • Can take parameters
  • Can be overloaded
  • Are invoked at the point of creation using the new keyword
the default constructor
The Default Constructor
  • What happens if you do not declare a constructor?
  • In these cases Java creates an invisible default constructor for you
  • The default constructor takes no parameters and contains no behavior. But allows you to create Object instances
  • We’ve been using them from day one
    • Dog d = new Dog();
summary
Summary
  • Recap
    • Variables, Scope and Methods
  • AccessorMethods
    • Getters and Setters
  • Encapsulation
    • public and protected
  • Constructors