4.1 objects
A program is composed of generic objects, with certain standard properties, and certain standard operations the objects can perform. In object oriented programming (OOP), you only care about what the objects expose. You won't be able to determine how someone else's object functions. In fact, the public method (interface) is more important.
In traditional procedural programming, you search for verbs (actions) in the problem definition. In procedural programming. verbs directly suggest procedures and then, lastly, you think of data variables to go with those procedures. In OOP, you put data structures first, and then look at the algorithms that operate on the data. The secret to effective OOP is that each object carries out a small set of related tasks. If an object needs a task done but that task isn't the job of that object then that object asks another object to do the task.
Again, since the first object can't do the task, it asks the second object to carry out the task. In OOP, one object must never directly manipulate the internal data of another object. Rather, all communication is via "messages". A message is another name for a method call.
4.2 Classes
The term class is the blueprint or recipe from which the object is actually made, or "instantiated."
Myclass boop;
boop = new MyClass ( ) ;
we are now familiar with this the first "MyClass boop; " makes a reference called "boop." At this point, the reference called "boop" does not actually point to any existing object. soon, if will point to an object of type MyClass, but now the object doesn't exist.
MyClass boop = new Myclass ( ) ;
When this statement executes the new keyword executes the default Constructor for MyClass which actually creates an object in memory and assigns that reference to boop. The handle to the just-created object is given to the MyClass reference boop. Now boop points to the new MyClass object.All the instances of a class have the same instance variables, with different values inside them. The state or current values of those variables define the current situation or state of this instance of the class. For example, a class called Hourly Employee contains instance variables:
first_name
last_name
soc_sec_number
hourly_rate
current_vacation_time
All objects that are instances of the same class share the same behavior. They all have the same methods. We could send the same messages all instances of the a class and all would understand and respond to the messages.
our class is: Hour1yEmployee
All instances of this class have these methods:
calculate_pay ( )
setName ( )
getName ( )
setSSN ( )
getSSN ( )
getVacationTime ( )
getHourlyRate ( )
setHourluRate ( )
Every example, or instantiation of this class has the same method (behavior) available to it.
Let's instantiate Hourly Employee:
HourlyEmployee joseph; // empty reference.
joseph = new hourlyEmployee ('Joe' 'smith', '598-22-7893', '$10.00', '22.25') ;
Now, we've created an instance of the class Hourly Employee. Our class is: HourlyEmployee. We have instantiated HourlyEmployee and our instance is called joseph. The identity of the instance is joseph.
The state of the instance is:
first_name = ,,Joe
last_name = smith
soc_sec_number + 598-22-7893
hourly_rate = $10.00
current_vacation_time = 22.25
The behavior of the instance is:
HourlyEmployee ravi;
marie = new HourlyEmployee ('Ravi' , 'J', '555-24-1516'. 'Rs.30.00', '0')
HourlyEmployee rahul;
Theodore = new HourlyEmployee ('Ted', 'L', '681-22-9875', 'Rs.10.00', '22') ;
HourlyEmployee priya;
david = new HourlyEmployee ('Dave', 'D', '198-99-0098', 'Rs.15.00','8') ;
Identity is the reference to this instantiation. All three have the exact same behavior. The state of each instance is defined by its instance variables. The state of an instance can only be changed by going through its methods or behavior.
4.2.1 Class scope
A class's instance variables and methods have a thing called "class scope" Within the class (or scope of that class). class member variables are accessible by name. So, inside or outside of any method in the class, those instance variables can be reached from anywhere in the class. If a member variable has been declared public, then it can be accessed outside of the class by simply referencing as follows:
ClassName.primitive_variable
ClassName.object_variable.
Another instance of this class has access to the instance variables in any other instance of this class. You can use the instance identifier or the class name if it declared as a "static" variable.
4.2.2 Cosmic Base Class
In Java, all classes are built on other classes. Ultimately, all classes in java stem from one central "Cosmic Base Class" called object. Even if you didn't use the word "extends" in your class definition, you're still always extending object by default.
When you extend any "Base Class", the new (derived) class has all the properties (instance variables) and methods of its parent, or Base Class. You can choose to modify or keep any method of the parent, or you can create methods that only apply to the child or "inherited" class.
The concept of extending a base class is called "Inheritance." inheritance is the second fundamental concept of object-oriented programming Encapsulation is the first, Polymorphism is the third.
4.2.3 Relationships between classes
Classes can be related to each other in one of three alternative way:
use
containment ( "has—a" )
inheritance ( "is – s " )
When one class sends messages to another class, we say it "uses" the class that receives its messages. When one class lives as an Instance variable within another class, we say it is "Contained", a "has-a" relationship, when one class inherits from another class, we say it is an "is-a" relationship.
Imagine that we have a class order. Class order needs to use the class Account, in order to check for credit status. Generally, if a method of class order sends a message to an object of class Account, then order uses Account, In other words, order uses Account when order calls methods of Account.
A method of order: creates, receives or returns objects of class Account. The "Containment" relationship also known as the "Composition" relationship is special case of the "use" relationship. In a Containment composition relationship, at least one method of one class actually contains an object of another class. In the use relationship, it calls methods of another object. In the containment relationship, it contains another object. In a "has-a" relationship, a class become an instance variable for the class we are defining.
Inheritance means specialization. When we inherit from a class, we wish to keep nearly everything in the base class (Superclass). In inheritance, we seek to elaborate on what we wish to create subclass off of order. Our subclass is called Rushorder.
Class Rushorder has everything that order has, but it adds a few instance variables, may be adds a method or two and overrides a methods or two.
The three relationships between classes which form the foundation of object-oriented Design are, use, "has-a" and "is-a".
4.2.4 Techniques for using objects
We have spent a lot of time emphasizing the difference between a reference and the object to which it refers.
JLabel howdy;
howdy = new JLabel ( "How Are ya?" ) ;
Here howdy is reference. We start off by declaring reference "howdy" to an object of type JLabel. Then, we instantiate the object by calling its constructor with the new keyword, and assign the handle to this instantiation to the reference we declared: "howdy".
howdy = new JLabel ( "How Are ya?" ) ;
okay, what happens when we execute the following statement?
JLabel hello; // A new reference
hello = howdy;
Now, both references point to the exact same object. Any changes made from howdy will be reflected in hello.
4.2.5 Controlling access to methods and variables
Public lets clients see the services (methods) the class provides (which means view the interface). The interface is the collective name for all the various methods that are available in the class. Methods should be public.
Private is the default setting. It hides implementation details. Private data members (variables) are only accessible through the public interface (Accessor methods) using public methods. Only utility methods should be made private. Utility methods are used only within the class.
Package is used when you don't specify that a method or a data variable is either private or public. If your program has only one class definition this change is transparent. If you don't specify either public or private for any feature meaning class, method or variable it can be accessed by all method in the same package. so, if you have the following field in your class:
public class Myclass
{
int mySalary;
…
}
…
and your class is stored in java.util.*; then any other method in any class that is also stored in this package can change this variable to anything it wants. What's more, anybody can add their own class to any package. And if you have a method to exploit that variable with package access, you could do anything you wanted! So, if your program uses many classes that are stored in the same package, they can directly access each other's package- access methods and data variables. They only need to use the reference. Variable to do so.
int minute; // minute declared without public
// or private.
Time2.minute // other members of its class can
// directly access minute.
4.3 Creating a package
A package is way to organize classes. Normally, you create a public class you don't define your class as public, then it's only accessible to other classes in the same package. Use the keyword package followed by the location.
Package com.sun.java;
The package statement must be the first statement in your class file compile it in DOS using the – d option
javac –d Time2.java
4.4 Final instance variables
The principle of encapsulation is built around the idea of limiting access to variables. This "least privilege" concept can be expanded to include variable that should never be changed, or "constants". Since this value is a constant, the compiler could optimize by replacing references to that variable with its constant value. Then there is no need to look up its value when it is referenced.
If a variable is defined as being "final" then it must be initialized in the same statement. It can never again be changed. By custom, it should be declared as all upper case. Any internal words in the identifier should be separated by underscores. If you try to change a variable that you earlier declared as being "final". Then the compiler will complain. Obviously, it is better to have the compiler complain, then to have your program crash in production. Whether or not variable is final is independent of its access. I.e., it can be declared either public or private.
private final int NUMBER_OF_MONTHS = 12;
final string FIRST_MONTH = "January";
4.5 Final methods and classes
when a method is declared to be final, java knows that the method can never be overridden. A Final method must be fully defined when it is declared. You cannot, for example, have an abstract final method. Since it is final, and can never be overridden by subclasses, the java compiler can replace the call to the method with inline code if it wants. As for security, if you declare a method to be final, then you can be sure it isn't overridden. For example, class object has a method called get class () that is declared final. No subclass can override this method and thereby return some other class type to hide its identity.
A final class makes all of its methods final as well, since a final class cannot be extended. Examples of final classes are: Integer, Long, Float and Double. None of these "wrapper" classes can be sub classed. String is another class that's declared final, So, if you want to stop programmers from every making a subclass of a particular class, you can declare that class to be final.
4.6 Objects passed by reference
As we know, the name or reference for an object represents a memory location where the object is stored. When an object passed, only the reference is passed. That means, only the address of the object is passed. A copy is not made of the object. This will have interesting implications.
Up until now. Our classes have either been Applets or Applications. Now we create a class that is neither. This class cannot execute unless it is instantiated by either an Application or an Applet. First we create the class. Then we create another Applet/Application class to test it.
4.7 Types of methods
The different kinds of methods are:
Constructor — instantiates the class.
Accessor—accesses the members' variables in the class.
Mutator—(also called Manipulator)— to change or write to the members variables of the class.
Utility— private methods that do work for the other methods of the class.
4.8 Our new class
Now we have a new class Time1. Class Time1 keeps time variables. The class also validates any time we wish to create. It prevents us from creating and impossible time. As of yet, there is no actual object. Right now, it is only a recipe for an object of our type. In other words, we haven't instantiated it yet. We cannot instantiate it in this class. We need to create another class to do TimeTest.java. The only purpose of this new class is to instantiate and test our new class Time1.
import javax.swing.JoptionPane;
Public class TimeTest
{
Public static void main (string args [ ] )
{
Time1 t = new Time1 ( ) ; // calls Time1 constructor
}
}
Now we have a new class Time1. Class Time1 keeps times variables. The class also validates any time we wish to create. It prevents us from creating an impossible time. As of yet, there is no actual object. Right now, it is only a recipe for an object of our type. In other words, we haven't instantiated it yet. We cannot instantiate it in this class. We need to create another class to do actually make an example of this class. We need to create a driver program TimeTest.java. The only purpose of this new class is to instantiate and test our new class Time1.
import javax.swing.JoptionPane;
public class TimeTest
{
Time t = new Time1 ( ) ; // calls Time1 constructor
}
}
Now we are using the class Time1 that we just created. This line creates a reference "t" to an object of type Time1, the "new Time10 calls the Constructor method to instantiate our new Time1 object "t".
import javax.swing.JoptionPane;
public class TimeTest
{
Public static void main (string args [ ] )
Time t = new Time1 ( ) ; // calls Time1 constructor
string output;
output = "The initial universal time is: " +
t. toUniversalstring ( ) + "/nThe initial time is: " +
t. tostring ( ) = "/nInplicit toString ( ) call: " + t;
system.exit (0) ;
}
}
In the next line, you see how we are calling two different methods of our new class. We're calling toUniversalString() and toString (). One curious things is this naked reference "t" sitting out here by itself. What does that do? Well. anytime you concatenate an object to a String you automatically cal its toString method.
4.9 Varieties of Methods: details
In applications we have created so far, there has only been the method main, In the applets we have created, there have been several standard methods: init ( ). start ( ) and paint ( ). Applets have other standard methods. as we know. The class we created Time1 is neither an application nor an applets. Time1 cannot execute unless another program first instantiates it. Encapsulating data and the methods used to access that data is the central role of the methods used to access that data is the central role of the class in object oriented programming. With this class, we make variables. There are several different varieties of methods, and each kind has a different sort of job to do.
Constructors—public methods used to initialize a class.
Accessors—public methods (gets) used to read data.
Mutators—public methods (sets) used to change data.
Utility—private methods used to serve the needs of other public methods.
Finalizer—protected methods used to do termination housekeeping.
The Constructor is named exactly the same as the class. It is called when the new keyword is used. It cannot have any return type, not even void. It instantiates the objects. It initializes instance variables to acceptable values. The "default" Constructor accepts no arguments. The Constructor method is usually overloaded. The overload Constructor usually takes arguments. That allows the class to be instantiated in a variety of ways. If the designer neglects to include a constructor, then the compiler creates a default constructor that takes no arguments. A default constructor will call the constructor for the class this one extends.
public Time2 ( )
{
setTime (0,0,0) ;
}
This is the first Constructor, Notice that it takes no arguments, but it still sets the instance variables for hour, minute and second to consistent initial values of zero.
public Time2 ( )
{
setTime (0,0,0) ;
}
public Time2 ( int h, int m, int s )
{
setTime ( h, m, s, ) ;
}
These are the first two constructors. The second one overrides the first. The second Constructor takes arguments. It still calls the setTime() method so it can validate the data.
Accessors are a public method to display private variables. The access to private member variables is provided through the Acessor, or "gets" methods. This allows the designer of the class to control how and anyone can access the private data. They are also called Query methods. Public methods used to change private variables. Mutators "set" private data. The designer can filter he incoming data and ensure it is correct before it is used to change the private data and ensure it is correct before it is used to change the private data. This permits the data to be correctly validated before it is used to update the member variables.
• You were sitting in your Ferrarri in your driveway.
• Next door, your plumber neighbor was sitting in her ferrarri
• If you wanted to refer to your neighbor's Ferrarri, you would naturally say "Jane's Ferrarri…."
• Likewise, it would be perfectly natural for you to refer to the car you were sitting in as "this Ferrarri…."
4.10 Finalize methods
We know that the constructor method is used to instantiate and initialize an object in memory. To avoid the problem called a "memory leak" one which plagues the C/C++ environment it is beneficial to have an anti-constructor method. Such methods exit. They are called Finalizer, and they control the orderly removal of objects from memory. When an object has gone out of scope, the finalizer executes automatically to clean up (release) used system resources. When there are no longer any references to an object, it is eligible for garbage collection is done automatically to return RAM memory back to the system—so called "Termination housekeeping."
We say that an unused object is marked for garbage collection. A finalizer method must always be called finalize () It always takes no arguments and returns void. The finalilze() method is one of the 11 methods inherited from method object.
4.11 Static class methods
When we instantiate a class, each instantiation of that class gets its own private copies of the instance variables for that class. However, in certain cases, we would like to have all the instances of the class share one copy of a variable, instead of each having their own copy.
interestRate
Say we had 30,000 instances of a class called savings Account. if we changed the interestRate variable they all contained, we would have to make 30,000 method calls to make the change in all of them. However, if we just had defined the interest variable as static, we would have only a single copy that of them shared.
Static interestRate
Only the members of the class could access the static variable. Instance variables that are defined as being static have class scope. If you define your static instance variables as public.
public int static interestRate
then this variable can be reached by a reference to any object of that class, or through the class name using the dot operator:
savacct.interestRate
or
savingAccount.interestRate
or
className.staticFieldName;
if you define your static instance variables as private:
private int static interestRate
Then the private static instance variables can only be accessed through methods of the class. Like any other private variable. Static Class members can be accessed even when no instances of that class exist, To access a public static class members when the class is not instantiated, you tack the name of the class to the name of the variable:
savingsAccount.interestRate
Math.PI is a static member variable
To access a private static class member when the class is not instantiated you still prefix with the class name, but then you also use a public static method:
savingsAccount.getInterestRate ( )
When even a single instance of the class SavingsAccount exists (is instantiated), then any of those existing classes can access our static variable (interestRate) simply by using its name: interestRate. When no objects of class SavingsAccount exist, our static variable can still be referened, but only by going through the class name and public static method:
SavingsAccount.getInterestRate ( )
Just like static class members (data variables), belong to the class not any one instance of a class. That means you can use them without creating any instance of a class. For example, all the methods built into the Math class are static methods. You use this general syntax when using:
ClassName.StaticMethod (Parameters) :
Because static methods do not work with an instance of a class, they can only access static fields. Let's think about this: NO instance of the class is instantiated .In this situation, the only thing that could possibly be present is a static member. Thus, the only thing that would be around for a static method to see is another static member. Finally, consider the most famous of all static methods.
public static void main (string args [ ] )
Since main is static. you don't need to create an instance of the class in order to call it—and the Java interpreter doesn't either. Once again, "static" means: variables and methods that belong to a class but not to any particular object of the class
A program is composed of generic objects, with certain standard properties, and certain standard operations the objects can perform. In object oriented programming (OOP), you only care about what the objects expose. You won't be able to determine how someone else's object functions. In fact, the public method (interface) is more important.
In traditional procedural programming, you search for verbs (actions) in the problem definition. In procedural programming. verbs directly suggest procedures and then, lastly, you think of data variables to go with those procedures. In OOP, you put data structures first, and then look at the algorithms that operate on the data. The secret to effective OOP is that each object carries out a small set of related tasks. If an object needs a task done but that task isn't the job of that object then that object asks another object to do the task.
Again, since the first object can't do the task, it asks the second object to carry out the task. In OOP, one object must never directly manipulate the internal data of another object. Rather, all communication is via "messages". A message is another name for a method call.
4.2 Classes
The term class is the blueprint or recipe from which the object is actually made, or "instantiated."
Myclass boop;
boop = new MyClass ( ) ;
we are now familiar with this the first "MyClass boop; " makes a reference called "boop." At this point, the reference called "boop" does not actually point to any existing object. soon, if will point to an object of type MyClass, but now the object doesn't exist.
MyClass boop = new Myclass ( ) ;
When this statement executes the new keyword executes the default Constructor for MyClass which actually creates an object in memory and assigns that reference to boop. The handle to the just-created object is given to the MyClass reference boop. Now boop points to the new MyClass object.All the instances of a class have the same instance variables, with different values inside them. The state or current values of those variables define the current situation or state of this instance of the class. For example, a class called Hourly Employee contains instance variables:
first_name
last_name
soc_sec_number
hourly_rate
current_vacation_time
All objects that are instances of the same class share the same behavior. They all have the same methods. We could send the same messages all instances of the a class and all would understand and respond to the messages.
our class is: Hour1yEmployee
All instances of this class have these methods:
calculate_pay ( )
setName ( )
getName ( )
setSSN ( )
getSSN ( )
getVacationTime ( )
getHourlyRate ( )
setHourluRate ( )
Every example, or instantiation of this class has the same method (behavior) available to it.
Let's instantiate Hourly Employee:
HourlyEmployee joseph; // empty reference.
joseph = new hourlyEmployee ('Joe' 'smith', '598-22-7893', '$10.00', '22.25') ;
Now, we've created an instance of the class Hourly Employee. Our class is: HourlyEmployee. We have instantiated HourlyEmployee and our instance is called joseph. The identity of the instance is joseph.
The state of the instance is:
first_name = ,,Joe
last_name = smith
soc_sec_number + 598-22-7893
hourly_rate = $10.00
current_vacation_time = 22.25
The behavior of the instance is:
HourlyEmployee ravi;
marie = new HourlyEmployee ('Ravi' , 'J', '555-24-1516'. 'Rs.30.00', '0')
HourlyEmployee rahul;
Theodore = new HourlyEmployee ('Ted', 'L', '681-22-9875', 'Rs.10.00', '22') ;
HourlyEmployee priya;
david = new HourlyEmployee ('Dave', 'D', '198-99-0098', 'Rs.15.00','8') ;
Identity is the reference to this instantiation. All three have the exact same behavior. The state of each instance is defined by its instance variables. The state of an instance can only be changed by going through its methods or behavior.
4.2.1 Class scope
A class's instance variables and methods have a thing called "class scope" Within the class (or scope of that class). class member variables are accessible by name. So, inside or outside of any method in the class, those instance variables can be reached from anywhere in the class. If a member variable has been declared public, then it can be accessed outside of the class by simply referencing as follows:
ClassName.primitive_variable
ClassName.object_variable.
Another instance of this class has access to the instance variables in any other instance of this class. You can use the instance identifier or the class name if it declared as a "static" variable.
4.2.2 Cosmic Base Class
In Java, all classes are built on other classes. Ultimately, all classes in java stem from one central "Cosmic Base Class" called object. Even if you didn't use the word "extends" in your class definition, you're still always extending object by default.
When you extend any "Base Class", the new (derived) class has all the properties (instance variables) and methods of its parent, or Base Class. You can choose to modify or keep any method of the parent, or you can create methods that only apply to the child or "inherited" class.
The concept of extending a base class is called "Inheritance." inheritance is the second fundamental concept of object-oriented programming Encapsulation is the first, Polymorphism is the third.
4.2.3 Relationships between classes
Classes can be related to each other in one of three alternative way:
use
containment ( "has—a" )
inheritance ( "is – s " )
When one class sends messages to another class, we say it "uses" the class that receives its messages. When one class lives as an Instance variable within another class, we say it is "Contained", a "has-a" relationship, when one class inherits from another class, we say it is an "is-a" relationship.
Imagine that we have a class order. Class order needs to use the class Account, in order to check for credit status. Generally, if a method of class order sends a message to an object of class Account, then order uses Account, In other words, order uses Account when order calls methods of Account.
A method of order: creates, receives or returns objects of class Account. The "Containment" relationship also known as the "Composition" relationship is special case of the "use" relationship. In a Containment composition relationship, at least one method of one class actually contains an object of another class. In the use relationship, it calls methods of another object. In the containment relationship, it contains another object. In a "has-a" relationship, a class become an instance variable for the class we are defining.
Inheritance means specialization. When we inherit from a class, we wish to keep nearly everything in the base class (Superclass). In inheritance, we seek to elaborate on what we wish to create subclass off of order. Our subclass is called Rushorder.
Class Rushorder has everything that order has, but it adds a few instance variables, may be adds a method or two and overrides a methods or two.
The three relationships between classes which form the foundation of object-oriented Design are, use, "has-a" and "is-a".
4.2.4 Techniques for using objects
We have spent a lot of time emphasizing the difference between a reference and the object to which it refers.
JLabel howdy;
howdy = new JLabel ( "How Are ya?" ) ;
Here howdy is reference. We start off by declaring reference "howdy" to an object of type JLabel. Then, we instantiate the object by calling its constructor with the new keyword, and assign the handle to this instantiation to the reference we declared: "howdy".
howdy = new JLabel ( "How Are ya?" ) ;
okay, what happens when we execute the following statement?
JLabel hello; // A new reference
hello = howdy;
Now, both references point to the exact same object. Any changes made from howdy will be reflected in hello.
4.2.5 Controlling access to methods and variables
Public lets clients see the services (methods) the class provides (which means view the interface). The interface is the collective name for all the various methods that are available in the class. Methods should be public.
Private is the default setting. It hides implementation details. Private data members (variables) are only accessible through the public interface (Accessor methods) using public methods. Only utility methods should be made private. Utility methods are used only within the class.
Package is used when you don't specify that a method or a data variable is either private or public. If your program has only one class definition this change is transparent. If you don't specify either public or private for any feature meaning class, method or variable it can be accessed by all method in the same package. so, if you have the following field in your class:
public class Myclass
{
int mySalary;
…
}
…
and your class is stored in java.util.*; then any other method in any class that is also stored in this package can change this variable to anything it wants. What's more, anybody can add their own class to any package. And if you have a method to exploit that variable with package access, you could do anything you wanted! So, if your program uses many classes that are stored in the same package, they can directly access each other's package- access methods and data variables. They only need to use the reference. Variable to do so.
int minute; // minute declared without public
// or private.
Time2.minute // other members of its class can
// directly access minute.
4.3 Creating a package
A package is way to organize classes. Normally, you create a public class you don't define your class as public, then it's only accessible to other classes in the same package. Use the keyword package followed by the location.
Package com.sun.java;
The package statement must be the first statement in your class file compile it in DOS using the – d option
javac –d Time2.java
4.4 Final instance variables
The principle of encapsulation is built around the idea of limiting access to variables. This "least privilege" concept can be expanded to include variable that should never be changed, or "constants". Since this value is a constant, the compiler could optimize by replacing references to that variable with its constant value. Then there is no need to look up its value when it is referenced.
If a variable is defined as being "final" then it must be initialized in the same statement. It can never again be changed. By custom, it should be declared as all upper case. Any internal words in the identifier should be separated by underscores. If you try to change a variable that you earlier declared as being "final". Then the compiler will complain. Obviously, it is better to have the compiler complain, then to have your program crash in production. Whether or not variable is final is independent of its access. I.e., it can be declared either public or private.
private final int NUMBER_OF_MONTHS = 12;
final string FIRST_MONTH = "January";
4.5 Final methods and classes
when a method is declared to be final, java knows that the method can never be overridden. A Final method must be fully defined when it is declared. You cannot, for example, have an abstract final method. Since it is final, and can never be overridden by subclasses, the java compiler can replace the call to the method with inline code if it wants. As for security, if you declare a method to be final, then you can be sure it isn't overridden. For example, class object has a method called get class () that is declared final. No subclass can override this method and thereby return some other class type to hide its identity.
A final class makes all of its methods final as well, since a final class cannot be extended. Examples of final classes are: Integer, Long, Float and Double. None of these "wrapper" classes can be sub classed. String is another class that's declared final, So, if you want to stop programmers from every making a subclass of a particular class, you can declare that class to be final.
4.6 Objects passed by reference
As we know, the name or reference for an object represents a memory location where the object is stored. When an object passed, only the reference is passed. That means, only the address of the object is passed. A copy is not made of the object. This will have interesting implications.
Up until now. Our classes have either been Applets or Applications. Now we create a class that is neither. This class cannot execute unless it is instantiated by either an Application or an Applet. First we create the class. Then we create another Applet/Application class to test it.
4.7 Types of methods
The different kinds of methods are:
Constructor — instantiates the class.
Accessor—accesses the members' variables in the class.
Mutator—(also called Manipulator)— to change or write to the members variables of the class.
Utility— private methods that do work for the other methods of the class.
4.8 Our new class
Now we have a new class Time1. Class Time1 keeps time variables. The class also validates any time we wish to create. It prevents us from creating and impossible time. As of yet, there is no actual object. Right now, it is only a recipe for an object of our type. In other words, we haven't instantiated it yet. We cannot instantiate it in this class. We need to create another class to do TimeTest.java. The only purpose of this new class is to instantiate and test our new class Time1.
import javax.swing.JoptionPane;
Public class TimeTest
{
Public static void main (string args [ ] )
{
Time1 t = new Time1 ( ) ; // calls Time1 constructor
}
}
Now we have a new class Time1. Class Time1 keeps times variables. The class also validates any time we wish to create. It prevents us from creating an impossible time. As of yet, there is no actual object. Right now, it is only a recipe for an object of our type. In other words, we haven't instantiated it yet. We cannot instantiate it in this class. We need to create another class to do actually make an example of this class. We need to create a driver program TimeTest.java. The only purpose of this new class is to instantiate and test our new class Time1.
import javax.swing.JoptionPane;
public class TimeTest
{
Time t = new Time1 ( ) ; // calls Time1 constructor
}
}
Now we are using the class Time1 that we just created. This line creates a reference "t" to an object of type Time1, the "new Time10 calls the Constructor method to instantiate our new Time1 object "t".
import javax.swing.JoptionPane;
public class TimeTest
{
Public static void main (string args [ ] )
Time t = new Time1 ( ) ; // calls Time1 constructor
string output;
output = "The initial universal time is: " +
t. toUniversalstring ( ) + "/nThe initial time is: " +
t. tostring ( ) = "/nInplicit toString ( ) call: " + t;
system.exit (0) ;
}
}
In the next line, you see how we are calling two different methods of our new class. We're calling toUniversalString() and toString (). One curious things is this naked reference "t" sitting out here by itself. What does that do? Well. anytime you concatenate an object to a String you automatically cal its toString method.
4.9 Varieties of Methods: details
In applications we have created so far, there has only been the method main, In the applets we have created, there have been several standard methods: init ( ). start ( ) and paint ( ). Applets have other standard methods. as we know. The class we created Time1 is neither an application nor an applets. Time1 cannot execute unless another program first instantiates it. Encapsulating data and the methods used to access that data is the central role of the methods used to access that data is the central role of the class in object oriented programming. With this class, we make variables. There are several different varieties of methods, and each kind has a different sort of job to do.
Constructors—public methods used to initialize a class.
Accessors—public methods (gets) used to read data.
Mutators—public methods (sets) used to change data.
Utility—private methods used to serve the needs of other public methods.
Finalizer—protected methods used to do termination housekeeping.
The Constructor is named exactly the same as the class. It is called when the new keyword is used. It cannot have any return type, not even void. It instantiates the objects. It initializes instance variables to acceptable values. The "default" Constructor accepts no arguments. The Constructor method is usually overloaded. The overload Constructor usually takes arguments. That allows the class to be instantiated in a variety of ways. If the designer neglects to include a constructor, then the compiler creates a default constructor that takes no arguments. A default constructor will call the constructor for the class this one extends.
public Time2 ( )
{
setTime (0,0,0) ;
}
This is the first Constructor, Notice that it takes no arguments, but it still sets the instance variables for hour, minute and second to consistent initial values of zero.
public Time2 ( )
{
setTime (0,0,0) ;
}
public Time2 ( int h, int m, int s )
{
setTime ( h, m, s, ) ;
}
These are the first two constructors. The second one overrides the first. The second Constructor takes arguments. It still calls the setTime() method so it can validate the data.
Accessors are a public method to display private variables. The access to private member variables is provided through the Acessor, or "gets" methods. This allows the designer of the class to control how and anyone can access the private data. They are also called Query methods. Public methods used to change private variables. Mutators "set" private data. The designer can filter he incoming data and ensure it is correct before it is used to change the private data and ensure it is correct before it is used to change the private data. This permits the data to be correctly validated before it is used to update the member variables.
• You were sitting in your Ferrarri in your driveway.
• Next door, your plumber neighbor was sitting in her ferrarri
• If you wanted to refer to your neighbor's Ferrarri, you would naturally say "Jane's Ferrarri…."
• Likewise, it would be perfectly natural for you to refer to the car you were sitting in as "this Ferrarri…."
4.10 Finalize methods
We know that the constructor method is used to instantiate and initialize an object in memory. To avoid the problem called a "memory leak" one which plagues the C/C++ environment it is beneficial to have an anti-constructor method. Such methods exit. They are called Finalizer, and they control the orderly removal of objects from memory. When an object has gone out of scope, the finalizer executes automatically to clean up (release) used system resources. When there are no longer any references to an object, it is eligible for garbage collection is done automatically to return RAM memory back to the system—so called "Termination housekeeping."
We say that an unused object is marked for garbage collection. A finalizer method must always be called finalize () It always takes no arguments and returns void. The finalilze() method is one of the 11 methods inherited from method object.
4.11 Static class methods
When we instantiate a class, each instantiation of that class gets its own private copies of the instance variables for that class. However, in certain cases, we would like to have all the instances of the class share one copy of a variable, instead of each having their own copy.
interestRate
Say we had 30,000 instances of a class called savings Account. if we changed the interestRate variable they all contained, we would have to make 30,000 method calls to make the change in all of them. However, if we just had defined the interest variable as static, we would have only a single copy that of them shared.
Static interestRate
Only the members of the class could access the static variable. Instance variables that are defined as being static have class scope. If you define your static instance variables as public.
public int static interestRate
then this variable can be reached by a reference to any object of that class, or through the class name using the dot operator:
savacct.interestRate
or
savingAccount.interestRate
or
className.staticFieldName;
if you define your static instance variables as private:
private int static interestRate
Then the private static instance variables can only be accessed through methods of the class. Like any other private variable. Static Class members can be accessed even when no instances of that class exist, To access a public static class members when the class is not instantiated, you tack the name of the class to the name of the variable:
savingsAccount.interestRate
Math.PI is a static member variable
To access a private static class member when the class is not instantiated you still prefix with the class name, but then you also use a public static method:
savingsAccount.getInterestRate ( )
When even a single instance of the class SavingsAccount exists (is instantiated), then any of those existing classes can access our static variable (interestRate) simply by using its name: interestRate. When no objects of class SavingsAccount exist, our static variable can still be referened, but only by going through the class name and public static method:
SavingsAccount.getInterestRate ( )
Just like static class members (data variables), belong to the class not any one instance of a class. That means you can use them without creating any instance of a class. For example, all the methods built into the Math class are static methods. You use this general syntax when using:
ClassName.StaticMethod (Parameters) :
Because static methods do not work with an instance of a class, they can only access static fields. Let's think about this: NO instance of the class is instantiated .In this situation, the only thing that could possibly be present is a static member. Thus, the only thing that would be around for a static method to see is another static member. Finally, consider the most famous of all static methods.
public static void main (string args [ ] )
Since main is static. you don't need to create an instance of the class in order to call it—and the Java interpreter doesn't either. Once again, "static" means: variables and methods that belong to a class but not to any particular object of the class