Classes in Java - PowerPoint PPT Presentation

1 / 26
About This Presentation
Title:

Classes in Java

Description:

public Employee(String n, double s, Day d) If no constructor is defined, the system default ... if (d1==d2) System.out.println('Oops...messed up again! ... – PowerPoint PPT presentation

Number of Views:35
Avg rating:3.0/5.0
Slides: 27
Provided by: crc7
Category:
Tags: classes | java | messedup

less

Transcript and Presenter's Notes

Title: Classes in Java


1
Classes in Java
  • class Employee
  • public Employee(String n, double s, Day d)
  • name n
  • salary s
  • hireDay d
  • public void print()
  • System.out.println(name " " salary "
    "
  • hireYear())
  • public void raiseSalary(double byPercent)
  • salary 1 byPercent / 100
  • public int hireYear()
  • return hireDay.getYear()

2
Methods in the Employee Class
  • Constructors
  • public Employee(String n, double s, Day d)
  • If no constructor is defined, the system default
    constructor will be called automatically.
  • Primitive instance variables and object instance
    variables will be initialized numeric type to
    zeros, boolean to false, and object variables to
    null.

3
Methods in Employee Class
Accessors/Interrogators/Queries public void
print() public int hireYear() Access but no
change to the state of an object. Manipulators/Mut
ators/Actions public void raiseSalary(double
byPercent) Change the state of an object. Private
methods can also be defined for implementing
internal methods.
4
Instance Variables
  • Instance variables are not initialized until a
    class is instantiated to an object.
  • Private instance variables are visible with the
    class in which they are declared vs. public
    instance variable are visible to the outside
    world.
  • Default constructor initializes instance
    variables to their default values.
  • We probably want to keep as many instance
    variables private as possible. However, this
    implies a public accessor and a public mutator
    are needed.

5
Driver
  • public class EmployeeTest
  • public static void main(String args)
  • Employee staff new Employee3
  • staff0 new Employee("Harry Hacker",
    35000,
  • new Day(1989,10,1))
  • staff1 new Employee("Carl Cracker",
    75000,
  • new Day(1987,12,15))
  • staff2 new Employee("Tony Tester",
    38000,
  • new Day(1990,3,15))
  • int i
  • for (i 0 i lt staff.length i)
    staffi.raiseSalary(5)
  • for (i 0 i lt staff.length i)
    staffi.print()

6
User Defined Default Constructor
  • Once a user defined constructor is declared. The
    systems default constructor ceased to exist.
  • How about adding the following default
    constructor to Employee?
  • public Employee()
  • What values will be stored in the instance
    variables during instantiation?
  • So, whats the problem?

7
  • public class EmployeeTest
  • public static void main(String args)
  • //...
  • Employee e new Employee()
  • e.print()
  • class Employee
  • public Employee()
  • public void print()
  • System.out.println(name " " salary "
    "
  • hireYear())
  • public int hireYear()
  • return hireDay.getYear()

8
UML Class Diagrams(for Static Modeling)
9
UML Object Diagram(for Static Modeling)
10
Mutable Objects Accessors
  • Consider the getHireDay() methods that returns a
    Day object to the caller.
  • public Day getHireDay()return hireDay
  • Vs. another accessor method that returns a
    String, which is immutable.
  • pubic String getName()return name
  • Similar to parameter passing and assignment,
    primitive types are returned by value and objects
    are returned by "reference".

11
Aliasing
  • The following piece of code generates aliases for
    the same object
  • Employee harry new Employee()
  • Day d harry.getHireDay()
  • d.advance(-3650) //go back 10 years

12
Cloning
  • How about making hireDay final?
  • A solution to this is cloning.
  • public Day getHireDay()
  • return (Day) hireDay.clone()
  • clone() belongs to java.lang and it returns
    Object.

13
Day's cloning method
  • class Day implements Cloneable
  • //...
  • public Object clone()
  • try
  • //a lazy way to do shallow copy on
    variables
  • return super.clone()
  • catch (CloneNotSupportedException e)
  • // this shouldn't happen, since we are
    Cloneable
  • System.out.println("Bombed")
  • return null
  • private int day
  • private int month
  • private int year

14
More on cloning
  • .clone() is defined for the Object class.
  • To make a class cloneable, that class has to
    implement the cloneable interface and redefine
    its only .clone() method.
  • class Employee implements Cloneable
  • //...
  • public Object clone()
  • try
  • return super.clone()
  • catch (CloneNotSupportedException e)
  • // this shouldn't happen, since we are
    Cloneable
  • System.out.println("Bombed")
  • return null
  • //...

15
Shallow Copy
  • public class EmployeeTest2
  • public static void main(String args)
  • Employee a new Employee("Harry Hacker",
    35000,
  • new Day(1989,10,1))
  • Employee b (Employee) a.clone()
  • Day d1 a.getHireDay()
  • Day d2 b.getHireDay()
  • if (d1d2)
  • System.out.println("Oops...messed up again!" )

16
Deep Copy with Copy Constructor?
  • public Employee(Employee rhs)
  • name new String(rhs.name) //String not
    cloneable
  • salary rhs.salary
  • hireDay (Day) rhs.hireDay.clone()
  • //Day has no constructor
  • If an instance variable is an object, its copy
    constructor should also perform deep copy.

17
Driver
  • public class EmployeeTest3
  • public static void main(String args)
  • Employee a new Employee("Harry Hacker",
    35000,
  • new
    Day(1989,10,1))
  • Employee b new Employee(a)
  • Day d1 a.getHireDay()
  • Day d2 b.getHireDay()
  • if (d1d2) System.out.println("Oops...messed
    up again!")
  • When you need to return an object by-value with
    deep copy in a method, say Employee, try
  • return new Employee(this) //this or some
    Employee variable.

18
Do we need to perform deep copy on Strings?
public Employee(Employee rhs) //name new
String(rhs.name) name rhs.name salary
rhs.salary hireDay (Day) rhs.hireDay.clone()

19
A better way Cloneable Employee
class Employee implements Cloneable //. . .
public Object clone() try //using
super.clone() to do shallow copy // a lazy way
to do it Employee tmp (Employee)
super.clone() tmp.hireDay (Day)
hireDay.clone() return tmp catch
(CloneNotSupportedException e) // this
shouldn't happen, since we are Cloneable
System.out.println("Bombed")
return null
20
Class Variables
  • Variables declared with static.
  • Similar to class methods (static methods), such
    variables belongs to a class rather than an
    object.
  • They can be initialized using an initialization
    block.
  • Non-static variables can also be initialized
    here.

public class Numeric //... public static int
multi(int a, int b) return
(ab) private static double buffer new
doubleMAXSIZE private static int
size static //initialization block size
100 for (int i0 iltbuffer.length
i) bufferi Math.random()
21
Good Programming Practices
  • There are three ways to initialize instance
    variables
  • In constructors.
  • Using initialization block (similar to statics).
  • Instance field initialization.
  • public class MyClass
  • //
  • private final int i0 //OK
  • private int j
  • private static double x
  • private static final double y0
  • //initialization block
  • j 0 //better do it in constructor
  • static //static initialization block
  • x0

22
Order of Execution
  • When an object is being created
  • Class variables are created and the static
    initializers are executed. (First time only)
  • The static initialization block is executed.
  • Instance variables are created and the
    initializers are executed.
  • The initialization block is executed.
  • The body of the constructor is executed.

23
Test Program
  • class MyClass
  • public MyClass()System.out.println("MyClass
    Constructor")
  • private static int f()System.out.println("Initia
    lizer")return 0
  • private static double g()System.out.println("Sta
    tic Initializer") return 0
  • private final int if()
  • private int j
  • private static double x
  • private static final double yg() //OK
  • //initialization block
  • j 0 //better do it in constructor
  • System.out.println("Initialization Block")
  • static
  • x0 //OK
  • System.out.println("Static Initialization
    Block")

24
Driver Outputs
  • public class MyClassTest1
  • public static void main(String args)
  • MyClass a //nothing happens
  • MyClass b new MyClass()
  • MyClass c new MyClass()
  • Static Initializer
  • Static Initialization Block
  • Initializer
  • Initialization Block
  • MyClass Constructor
  • Initializer
  • Initialization Block
  • MyClass Constructor

25
Instance Variables that are Objects
  • class MyClass
  • public MyClass(int i)
  • System.out.println("MyClass Constructor")
  • part new Part(i)
  • //...
  • private Part part
  • //...
  • class Part
  • public Part(int i)System.out.println("Part
    Constructor")
  • private int k

26
Driver Outputs
  • public class MyClassTest2
  • public static void main(String args)
  • MyClass a new MyClass(1)
  • C creates instance variables implicitly first
    and then execute the constructors body.

Static Initializer Static Initialization
Block Initializer Initialization Block MyClass
Constructor Part Constructor
Write a Comment
User Comments (0)
About PowerShow.com