280 likes | 401 Views
Chapter 7 Object-Oriented Programing(2). Leturer: Ty Rasmey Email: rasmeyt2@gmail.com. Overview. Using Classes from Java Library Static Variable, Constant and Methods Visibility Modifier Data Field Encapsulation Immutable Objects and Classes Passing Object to Variables.
E N D
Chapter 7Object-Oriented Programing(2) Leturer: Ty Rasmey Email: rasmeyt2@gmail.com
Overview • Using Classes from Java Library • Static Variable, Constant and Methods • Visibility Modifier • Data Field Encapsulation • Immutable Objects and Classes • Passing Object to Variables
Using Classes from Java Library(1) The Date Class • Java provides a system-independent encapsulation of date and time in java.util.Date class. Constructs Date object for the current date time. Constructs a Date object for a given time in milliseconds elapsed since January 1, 1970, GTM. Returns a string representing the date and time. Returns the number of milliseconds since January 1970, GMT. Sets a new elapse time in the object The sign + indicates public modifier
Using Classes from Java Library(2) public class TestDate { public static void main(String[] args){ java.util.Date date = new java.util.Date(); System.out.println(“The elapsed time since Jan 1, 1970 is” + date.getTime() + “milliseconds”); System.out.println(date.toString()); }
Using Classes from Java Library(3) • The Random Class
Static Variables, Constants, and Methods(1) • Java member variable can be static or non-static. • Static variable belong to Java Class while non-static variable belong to object. • Static variable will keep same value for every object while the value of non-static variable varies from object to object. • An instance variable is tried to a specific instance of the class; it is not share among objects of the same class.
Static Variables, Constants, and Methods(2) • E.g. Suppose that you create the following objects: Circle circle1 = new Circle(); Circle circle1 = new Circle(5); • The radius in circle1 is independent of the radius in circle2 • Is stored in different memory location • Changes made to circle1’s radius do not affect circle2’s radius and vice versa
Static Variables, Constants, and Methods(3) • If you want all instances of a class share data use static variables • Static variables store the values for variables in common memory • Because of common memory location, all object of the same class are affected if one object change the value of a static variable.
Static Variables, Constants, and Methods(4) public class Circle2{ double radius; static int numberOfObjects = 0; Circle2(){ radius = 1; numberOfObjects++; } Circle2(double newRadius){ radius = newRadius; numberOfObjects++; } static int getNumberOfObjects(){ return numberOfObjects; } double getArea(){ return radius * radius * Math.PI; } }
Static Variables, Constants, and Methods(5) • Java support static methods as well as static variable. Static methods can be called without creating an instance of the class. • Method not marked with static keyword is an instance method • In order to call an instance method, you must first have an instance of class within which the method you want to call is defined. • Suppose we want to call an instance method named “method1” defined in class “ClassA”. ClassA x = new ClassA(); x.method1(); • if method 1 were instead static, then we would call the method by referring directly to the class itself: ClassA.method1();
Static Variables, Constants, and Methods(7) • Constants in class are shared by all object of the class. Thus, constants should be declared final static. • For Example constants PI in Math Class is defined as: final static double PI = 3.14159265358979323846;
Static Variables, Constants, and Methods(8) • Caution: public class Foo { int i = 5; static int k = 2; public static void main(String[] args) { int j = i; // Wrong because i is an instance variable m1(); // Wrong because m1() is an instance method } public void m1() { // Correct since instance and static variables and methods // can be used in an instance method i = i + k + m2(i, k); } public static int m2(int i, int j) { return (int)(Math.pow(i, j)); } }
Visbility Modifiers(1) • Java Provides several modifiers that control access to data field, methods, and classes: • public makes classes, constructor method, and data fields accessible from any class in any package • private makes methods and data field accessible only from within its own class. • If public orprivate is not used, then by default classes, methods, and data field are accessible by any class in the same package. This is known as package-private or package-access. • protected make constructor, methods or data field accessible in this package and in subclasses of this class in any package.
Visibilty Modifiers(2) • The private modifier restricts access to its defining a class, the default modifier restricts access to a package, and the public modifier enables unrestricted access.
Visibility Modifiers(3) • Non-public class has package-access • An object can access its private members if it is declared in its own class.
Data Field Encapsulation(1) • The data field radius and numberOfObjects in Circle2 class can be modified directly (myCircle.radius = 5 or Circle2.numberOfObjects = 10). This is not a good practice for two reasons: • Data may be tampered. For Example, numberOfObjects is to count the number of object created, but it may be set to an arbitrary value • It makes the class difficult to maintain and vulnerable to bug. To prevent direct modifications of properties, you should declare the field private, using the private modifier • Private data field cannot be accessed by object through a direct reference outside the class that defines the private field
Data Field Encapsulation(2) • But often a client needs to retrieve and modify a data field. • To make a private data field accessible, provide a get method to return the value of data field. public returnType getPropertyName(); • To enable a private data field to be updated, provide a set method to set new value public void setPropertyName(dataType propertyValue) Note: • If the returnType is boolean, the get method should be defined as public boolean isPropertyName().
Data Field Encapsulation(3) • The Circle class encapsulates circle properties and provides get/set and other methods. The radius of this circle(default: 1.0). The number of circle objects created. Constructs a default circle object. Constructs Circle object with the specific radius. Returns the radius of this circle. Set a new radius for this circle. Return the number of circle objects created. Return the area of this circle. The sign - indicates priivate modifier
public class TestCircle3 { • public static void main(String[] args){ • Circle3 myCircle = new Circle3(5.0); • System.out.println("The radius of Circle3 is "+myCircle.getRadius()+ • "and The area of Circle3 is "+ myCircle.getArea()); • //increase the radius of Cirlce3 by 10% • myCircle.setRadius(myCircle.getRadius() * 1.1); • System.out.println("The radius of Circle3 is "+myCircle.getRadius()+ • "and The area of Circle3 is "+ myCircle.getArea()); • } • } • Output: • The radius of Circle3 is 5.0and The area of Circle3 is 78.53981633974483 • The radius of Circle3 is 5.5and The area of Circle3 is 95.03317777109125
Immutable Objects and Classes(1) • If contents of an object cannot be changed once the object is created, the object is called an immutable object and its class is called an immutable class. public class Student { private int id; private BirthDate birthDate; public Student(int ssn, int year, int month, int day){ id = ssn; birthDate = new BirthDate(year, month, day); }public int getId(){ return id; } public BirthDate getBirthDate(){ return birthDate } }
Immutable Objects and Classes(2) public class BirthDate { private int year; private int month; private int day; public BirthDate(int newYear, int newMonth, int newDay) { year = newYear; month = newMonth; day = newDay; } public void setYear(int newYear) { year = newYear; } }
Immutable Objects and Classes(3) public class Test { public static void main(String[] args) { Student student = new Student(111223333, 1970, 5, 3); BirthDate date = student.getBirthDate(); date.setYear(2010); //Now the student birth year is changed! } } For a class to be immutable, it must mark all data fields private and provide no mutator methods and no accessor methods that would return a reference to a mutable data field object.
Passing Object to Method • So far, you have learned how to pass arguments of primitive types to methods. • You also pass object to methods. public class TestPassObject { public static void main(String[] args) { Circle3 myCircle = new Circle3(5.0); printCircle(myCircle); } public static void printCircle(Circle3 c) { System.out.println("The area of the circle of radius "+ c.getRadius() + " is " + c.getArea()); } }
public class TestPassObject { ** Main method */ public static void main(String[] args) { // Create a Circle object with radius 1 Circle3 myCircle = new Circle3(1); // Print areas for radius 1, 2, 3, 4, and 5. int n = 5; printAreas(myCircle, n); // See myCircle.radius and times System.out.println("\n" + "Radius is " + myCircle.getRadius()); System.out.println("n is " + n); } /** Print a table of areas for radius */ public static void printAreas(Circle3 c, int times) { System.out.println("Radius \t\t Area"); while (times >= 1) { System.out.println(c.getRadius() + "\t\t" + c.getArea()); c.setRadius(c.getRadius() + 1); times--; } } }
Summary • A class is a template for objects. It defines the generic properties of objects, and provides constructors for creating objects and methods for manipulating them. • A class is also a data type. You can use it to declare object reference variables. • An object is an instance of a class. You use the new operator to create an Object, and the dot(.) operator to access members of that object through its reference variable. • An instance variable or method belongs to an instance of a class. Its use is associated with individual instances. A static variable is a variable shared by all instances of the same class. A static method is a method that can be invoked without using instances.
Summary • Every instance of a class can access the class's static variables and methods. However, it is better to invoke static variables and methods using ClassName.variable and ClassName.method for clarity. • Modifiers specify how the class, method, and data are accessed. A public class, method, or data is accessible to all clients. A private method or data is only accessible inside the class. • You can provide a get method or a set method to enable clients to see or modify the data. Colloquially, a get method is referred to as a getter (or accessor), and a set method is referred to as a setter(or mutator).
Summary • A get method has the signature public returnType getPropertyName(). If the returnType is boolean, the get method should be defined as public boolean isPropertyName(). A set method has the signature public void setPropertyName(dataType propertyValue). • All parameters are passed to methods using pass-by-value. For a parameter of a primitive type, the actual value is passed; for a parameter of a reference type, the reference for the object is passed. • The scope of instance and static variables is the entire class, regardless of where the variables are declared. Instance and static variables can be declared anywhere in the class.
Summary • A Java array is an object that can contain primitive type values or object type values. When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types, ‘\u0000' for char types, false for boolean types, and null for object types. THE END