CS6308- Java Programming V P Jayachitra Assistant Professor Department of Computer Technology MIT Campus Anna University
• procedural programming: Programs that perform their behavior as a series of steps to be carried out. • object-oriented programming (OOP): Programs that perform their behavior as interactions between objects
About ? • The basic elements of a class • How a class can be used to create objects? • Learn about methods, constructors, and the this keyword.
Class • Any concept to implement in a Java program must be encapsulated within a class. • What is a class? • A class is a structure that defines the data and the methods to work on that data. • A new data type • A class is an encapsulation of attributes and methods. • A class is a logical construct or template.
Class Fundamentals • Class • Defines a new data type • A class is to create an object or instance of the defined type • A class is a template for an object • A class is the blueprint of an object • A class describe object’s properties and behaviors • Example: Blueprint of a house (class) and the house (object) Class Properties : State/variables Behaviors: Methods Class Clock Properties : State/variables int Hour, minute, second; Behaviors: Methods int getMinutes(); int getSeconds(); int getHours(); Blueprint public class Point { int x; int y; } Instance Point p=new Point();
Container class vs Definition class • Container class: • Collection of static methods that are not bound to a specific objects. • Example: Math.sqrt(), Math.pow() • Definition class: • A class that create new objects. • Example: Clock c1;
Object • Object • An object is an instance of a class. • An entity that combines state and behavior • An object is a real world entity. Characteristics of an Object: • State : represents the data (value) of an object. • Behavior : represents the behavior (functionality) of an object. • Identity : An object identity is typically implemented via unique ID. The value of the ID is not visible to the external user. However, JVM can identify each object uniquely.
Class Abstraction • Abstract data type (ADT) • Abstraction refers to the act of representing essential features without including the background details or explanations. • Class is an ADT as it uses the concept of abstraction. • Abstraction: • An abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. • Allow user to understand its external behaviour(interface) but not its internal details. • Example: Buttons • Why? To manage complexity • abstraction is achieved by using Interfaces and Abstract classes.
Encapsulation • State is encapsulated or hidden • The internal state of an object is not directly accessible to other parts of the program • Other parts of the program can only access the object using its interface. • Data-hiding: Data of a class is hidden from any other class and can be accessed only through any member function of it’s own class in which they are declared. Hours Minutes Seconds getMinutes() getHours() getSeconds()
General form of the class • The data, or variables, defined within a class are called instance variables. • Each instance of the class (that is, each object of the class) contains its own copy of these variables. • Thus, the data for one object is separate and unique from the data for another. • The code is contained within .defined within a class are called members of the class. • Classes have a main method(), if that class is the starting point of the program
A simple class Instance variables A class called Box that defines three instance variables: width, height, and depth. Class name A class defines a new type of data. In this case, the new data type is called Box. class name is used to declare objects of type Box. A class declaration only creates a template; It does not create an actual object. Object mybox will refer to an instance of Box. Thus, it will have “physical” reality. Each time on creating an instance of a class means creating an object that contains its own copy of each instance variable defined by the class Every Box object will contain its own copies of the instance variables width, height, and depth. To actually create a Box object, use a statement like the following: Box mybox = new Box(); // create a Box object called mybox
A simple class Dot operator Use the dot operator to access both the instance variables and the methods within an object. The dot operator links the name of the object with the name of an instance variable or methods. To actually create a Box object, use a statement like the following: Box mybox = new Box(); // create a Box object called mybox mybox.width = 100; //assign width variable of mybox the value 100
Save the file that contains this program BoxDemo.java, because the main( ) method is in the class called BoxDemo, not the class called Box. Compilation will create two .class files, one for Box and one for BoxDemo. Each class can also be defined in its own file, called Box.java and BoxDemo.java, Output: Volume is 3000.0
Every Box object will contain its own copies of the instance variables width, height, and depth. Changes to the instance variables of one object have no effect on the instance variables of another. Output : Volume is 3000.0 Volume is 162.0
Box mybox; // declare reference to object mybox = new Box(); // allocate a Box object Declare object The first line declares mybox as a reference to an object of type Box. At this point, mybox does not yet refer to an actual object. The next line allocates an object and assigns a reference to it to mybox. mybox simply holds the memory address of the actual Box object. Declaring Objects Declaring an object of type Box
new operator • The new operator dynamically allocates memory for an object. • The classname is the name of the class that is being instantiated. • The class name followed by parentheses specifies the constructor for the class. • A constructor defines what occurs when an object of a class is created. • Most real-world classes explicitly define their own constructors within their class definition. • However, if no explicit constructor is specified, then Java will automatically supply a default constructor. class-var = new classname ( );
Assigning Object Reference Variables • b1 and b2 will both refer to the same object. • The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. • It simply makes b2 refer to the same object as does b1. • Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object. • Assign one object reference variable to another object reference variable, is not creating a copy of the object, only making a copy of the reference. Box b1 = new Box(); Box b2 = b1; Box b1 = new Box(); Box b2 = b1; // ... b1 = null; Here, b1 has been set to null, but b2 still points to the original object.
Introducing Methods • Classes usually consist of two things: • instance variables • methods. • This is the general form of a method: type name(parameter-list) { // body of method return value; } Type Type specifies the type of data returned by the method. This can be any valid type, including class types If the method does not return a value, its return type must be void. Name The name of the method is specified by name. This can be any legal identifier . Parameter-list The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty. Return Methods that have a return type other than void return a value to the calling routine using the return statement:
Adding a Method to the Box Class Use methods to access the instance variables defined by the class. In fact, methods define the interface to most classes. This allows the class implementor to hide the specific layout of internal data structures behind cleaner method abstractions. In addition to defining methods that provide access to data, we can also define methods that are used internally by the class itself. Output: Volume is 3000.0 Volume is 162.0 No dot operator to access instance variable within the class dot operator used to access instance variable outside the class Instance variable that is not part of the class, it must be accessed through an object, by use of the dot operator. Instance variable that is part of the same class, that variable can be accessed directly. The same thing applies to methods.
Adding a Method That Takes Parameters • A parameterized method can operate on a variety of data. • A non parameterized method use is very limited parameter and argument: • A parameter is a variable defined by a method that receives a value when the method is called. • For example, in square( ), i is a parameter. • An argument is a value that is passed to a method when it is invoked. • For example, square(100) passes 100 as an argument. int x, y; x = square(5); // x equals 25 x = square(9); // x equals 81 y = 2; x = square(y); // x equals 4 parameter argument
mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; setDim( ) method to set the dimensions of each box.
Constructors • A constructor initializes an object immediately upon creation. • Automatic initialization of object is performed through the use of a constructor. • Constructor has the same name as the class in which it resides and is syntactically similar to a method. • Once defined, the constructor is automatically called when the object is created, before the new operator completes. • Constructor’s have no return type, not even void. • The implicit return type of a class’ constructor is the class type itself. Box mybox1 = new Box(); The parentheses are needed after the class name is to invoke the constructor for the class is being called.
Output: Constructing Box Constructing Box Volume is 1000.0 Volume is 1000.0
Default vs defined constructor • Java creates a default constructor for the class if a constructor is not explicitly defined for a class. • The default constructor will initialize all non initialized instance variables to their default values. • zero, null, and false, for numeric types, reference types, and boolean. • Once define your own constructor, the default constructor is no longer used.
Parameterized Constructor Parameterized Constructor Non-parameterized constructor allow all boxes to have the same dimensions. Parameterized constructor is a way to construct Box objects of various dimensions. Output: Volume is 3000.0 Volume is 162.0
The this Keyword • this keyword allows a method to refer to the object that invoked it. • this can be used inside any method to refer to the current object. • this is always a reference to the object on which the method was invoked. • use this anywhere as a reference to an object of the current class’ type.
this keyword:Instance Variable Hiding • It is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes. • There can be Overlap of local variables, including formal parameters to methods with the names of the class’ instance variables. • However, when a local variable has the same name as an instance variable, the local variable hides the instance variable. • this directly refers to the object, • use this to resolve any namespace collisions that might occur between instance variables and local variables.
A Stack Class
Garbage collections • In java, since objects are dynamically allocated by using the new operator, such objects are destroyed and their memory released for later reallocation automatically. • In some languages, such as traditional C++, dynamically allocated objects must be manually released by use of a delete operator. • It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. • There is no need to explicitly destroy objects. • Garbage collection only occurs sporadically (if at all) during the execution of your program.

java module 2java module 2java module 2java module 2

  • 1.
    CS6308- Java Programming VP Jayachitra Assistant Professor Department of Computer Technology MIT Campus Anna University
  • 3.
    • procedural programming:Programs that perform their behavior as a series of steps to be carried out. • object-oriented programming (OOP): Programs that perform their behavior as interactions between objects
  • 4.
    About ? • Thebasic elements of a class • How a class can be used to create objects? • Learn about methods, constructors, and the this keyword.
  • 5.
    Class • Any conceptto implement in a Java program must be encapsulated within a class. • What is a class? • A class is a structure that defines the data and the methods to work on that data. • A new data type • A class is an encapsulation of attributes and methods. • A class is a logical construct or template.
  • 6.
    Class Fundamentals • Class •Defines a new data type • A class is to create an object or instance of the defined type • A class is a template for an object • A class is the blueprint of an object • A class describe object’s properties and behaviors • Example: Blueprint of a house (class) and the house (object) Class Properties : State/variables Behaviors: Methods Class Clock Properties : State/variables int Hour, minute, second; Behaviors: Methods int getMinutes(); int getSeconds(); int getHours(); Blueprint public class Point { int x; int y; } Instance Point p=new Point();
  • 7.
    Container class vsDefinition class • Container class: • Collection of static methods that are not bound to a specific objects. • Example: Math.sqrt(), Math.pow() • Definition class: • A class that create new objects. • Example: Clock c1;
  • 8.
    Object • Object • Anobject is an instance of a class. • An entity that combines state and behavior • An object is a real world entity. Characteristics of an Object: • State : represents the data (value) of an object. • Behavior : represents the behavior (functionality) of an object. • Identity : An object identity is typically implemented via unique ID. The value of the ID is not visible to the external user. However, JVM can identify each object uniquely.
  • 9.
    Class Abstraction • Abstractdata type (ADT) • Abstraction refers to the act of representing essential features without including the background details or explanations. • Class is an ADT as it uses the concept of abstraction. • Abstraction: • An abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. • Allow user to understand its external behaviour(interface) but not its internal details. • Example: Buttons • Why? To manage complexity • abstraction is achieved by using Interfaces and Abstract classes.
  • 10.
    Encapsulation • State isencapsulated or hidden • The internal state of an object is not directly accessible to other parts of the program • Other parts of the program can only access the object using its interface. • Data-hiding: Data of a class is hidden from any other class and can be accessed only through any member function of it’s own class in which they are declared. Hours Minutes Seconds getMinutes() getHours() getSeconds()
  • 11.
    General form ofthe class • The data, or variables, defined within a class are called instance variables. • Each instance of the class (that is, each object of the class) contains its own copy of these variables. • Thus, the data for one object is separate and unique from the data for another. • The code is contained within .defined within a class are called members of the class. • Classes have a main method(), if that class is the starting point of the program
  • 12.
    A simple class Instancevariables A class called Box that defines three instance variables: width, height, and depth. Class name A class defines a new type of data. In this case, the new data type is called Box. class name is used to declare objects of type Box. A class declaration only creates a template; It does not create an actual object. Object mybox will refer to an instance of Box. Thus, it will have “physical” reality. Each time on creating an instance of a class means creating an object that contains its own copy of each instance variable defined by the class Every Box object will contain its own copies of the instance variables width, height, and depth. To actually create a Box object, use a statement like the following: Box mybox = new Box(); // create a Box object called mybox
  • 13.
    A simple class Dotoperator Use the dot operator to access both the instance variables and the methods within an object. The dot operator links the name of the object with the name of an instance variable or methods. To actually create a Box object, use a statement like the following: Box mybox = new Box(); // create a Box object called mybox mybox.width = 100; //assign width variable of mybox the value 100
  • 14.
    Save the filethat contains this program BoxDemo.java, because the main( ) method is in the class called BoxDemo, not the class called Box. Compilation will create two .class files, one for Box and one for BoxDemo. Each class can also be defined in its own file, called Box.java and BoxDemo.java, Output: Volume is 3000.0
  • 15.
    Every Box objectwill contain its own copies of the instance variables width, height, and depth. Changes to the instance variables of one object have no effect on the instance variables of another. Output : Volume is 3000.0 Volume is 162.0
  • 16.
    Box mybox; //declare reference to object mybox = new Box(); // allocate a Box object Declare object The first line declares mybox as a reference to an object of type Box. At this point, mybox does not yet refer to an actual object. The next line allocates an object and assigns a reference to it to mybox. mybox simply holds the memory address of the actual Box object. Declaring Objects Declaring an object of type Box
  • 17.
    new operator • Thenew operator dynamically allocates memory for an object. • The classname is the name of the class that is being instantiated. • The class name followed by parentheses specifies the constructor for the class. • A constructor defines what occurs when an object of a class is created. • Most real-world classes explicitly define their own constructors within their class definition. • However, if no explicit constructor is specified, then Java will automatically supply a default constructor. class-var = new classname ( );
  • 18.
    Assigning Object ReferenceVariables • b1 and b2 will both refer to the same object. • The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. • It simply makes b2 refer to the same object as does b1. • Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object. • Assign one object reference variable to another object reference variable, is not creating a copy of the object, only making a copy of the reference. Box b1 = new Box(); Box b2 = b1; Box b1 = new Box(); Box b2 = b1; // ... b1 = null; Here, b1 has been set to null, but b2 still points to the original object.
  • 19.
    Introducing Methods • Classesusually consist of two things: • instance variables • methods. • This is the general form of a method: type name(parameter-list) { // body of method return value; } Type Type specifies the type of data returned by the method. This can be any valid type, including class types If the method does not return a value, its return type must be void. Name The name of the method is specified by name. This can be any legal identifier . Parameter-list The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty. Return Methods that have a return type other than void return a value to the calling routine using the return statement:
  • 20.
    Adding a Methodto the Box Class Use methods to access the instance variables defined by the class. In fact, methods define the interface to most classes. This allows the class implementor to hide the specific layout of internal data structures behind cleaner method abstractions. In addition to defining methods that provide access to data, we can also define methods that are used internally by the class itself. Output: Volume is 3000.0 Volume is 162.0 No dot operator to access instance variable within the class dot operator used to access instance variable outside the class Instance variable that is not part of the class, it must be accessed through an object, by use of the dot operator. Instance variable that is part of the same class, that variable can be accessed directly. The same thing applies to methods.
  • 21.
    Adding a MethodThat Takes Parameters • A parameterized method can operate on a variety of data. • A non parameterized method use is very limited parameter and argument: • A parameter is a variable defined by a method that receives a value when the method is called. • For example, in square( ), i is a parameter. • An argument is a value that is passed to a method when it is invoked. • For example, square(100) passes 100 as an argument. int x, y; x = square(5); // x equals 25 x = square(9); // x equals 81 y = 2; x = square(y); // x equals 4 parameter argument
  • 22.
    mybox1.width = 10; mybox1.height= 20; mybox1.depth = 15; setDim( ) method to set the dimensions of each box.
  • 23.
    Constructors • A constructorinitializes an object immediately upon creation. • Automatic initialization of object is performed through the use of a constructor. • Constructor has the same name as the class in which it resides and is syntactically similar to a method. • Once defined, the constructor is automatically called when the object is created, before the new operator completes. • Constructor’s have no return type, not even void. • The implicit return type of a class’ constructor is the class type itself. Box mybox1 = new Box(); The parentheses are needed after the class name is to invoke the constructor for the class is being called.
  • 24.
  • 25.
    Default vs definedconstructor • Java creates a default constructor for the class if a constructor is not explicitly defined for a class. • The default constructor will initialize all non initialized instance variables to their default values. • zero, null, and false, for numeric types, reference types, and boolean. • Once define your own constructor, the default constructor is no longer used.
  • 26.
    Parameterized Constructor Parameterized Constructor Non-parameterizedconstructor allow all boxes to have the same dimensions. Parameterized constructor is a way to construct Box objects of various dimensions. Output: Volume is 3000.0 Volume is 162.0
  • 27.
    The this Keyword •this keyword allows a method to refer to the object that invoked it. • this can be used inside any method to refer to the current object. • this is always a reference to the object on which the method was invoked. • use this anywhere as a reference to an object of the current class’ type.
  • 28.
    this keyword:Instance VariableHiding • It is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes. • There can be Overlap of local variables, including formal parameters to methods with the names of the class’ instance variables. • However, when a local variable has the same name as an instance variable, the local variable hides the instance variable. • this directly refers to the object, • use this to resolve any namespace collisions that might occur between instance variables and local variables.
  • 29.
  • 30.
    Garbage collections • Injava, since objects are dynamically allocated by using the new operator, such objects are destroyed and their memory released for later reallocation automatically. • In some languages, such as traditional C++, dynamically allocated objects must be manually released by use of a delete operator. • It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. • There is no need to explicitly destroy objects. • Garbage collection only occurs sporadically (if at all) during the execution of your program.

Editor's Notes

  • #5 when you create a class, you are creating a new data type. You can use this type to declare objects of that type Object is a physical entity whereas class is a logical construct
  • #9 since the classes use the concept of data abstraction ,they are known as abstraction data type(ADT). Humans manage complexity through abstraction. When you drive your car you do not have to be concerned with the exact internal working of your car(unless you are a mechanic). What you are concerned with is interacting with your car via its interfaces like steering wheel, brake pedal, accelerator pedal etc. Various manufacturers of car has different implementation of car working but its basic interface has not changed (i.e. you still use steering wheel, brake pedal, accelerator pedal etc to interact with your car). Hence the knowledge you have of your car is abstract.
  • #10 Encapsulation or data-hiding.  Encapsulation can be achieved by declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.
  • #11 Variables defined within a class are called instance variables because each instance of the class (that is, each object of the class) contains its own copy of these variables. Thus, the data for one object is separate and unique from the data for another
  • #12 Currently, Box does not contain any methods (but some will be added soon). each time you create an instance of a class, you are creating an object that contains its own copy of each instance variable defined by the class
  • #13 Currently, Box does not contain any methods (but some will be added soon). each time you create an instance of a class, you are creating an object that contains its own copy of each instance variable defined by the class
  • #14 The Java compiler automatically puts each class into its own .class file. It is not necessary for both the Box and the BoxDemo class to actually be in the same source file. You could put each class in its own file, called Box.java and BoxDemo.java, respectively.
  • #17 Constructors are an important part of all classes and have many significant attributes. This is the case with Box. For now, we will use the default constructor. It is important to understand that new allocates memory for an object during run time. The advantage of this approach is that your program can create as many or as few objects as it needs during the execution of your program. However, since memory is finite, it is possible that new will not be able to allocate memory for an object because insufficient memory exists. If this happens, a run-time exception will occur. (You will learn how to handle exceptions ) Let’s once again review the distinction between a class and an object. A class creates a new data type that can be used to create objects. That is, a class creates a logical framework that defines the relationship between its members. When you declare an object of a class, you are creating an instance of that class. Thus, a class is a logical construct. An object has physical reality. (That is, an object occupies space in memory.) It is important to keep this distinction clearly in mind.
  • #19 type specifies the type of data returned by the method. This can be any valid type, including class types that you create. If the method does not return a value, its return type must be void. The name of the method is specified by name. This can be any legal identifier other than those already used by other items within the current scope. The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty.
  • #20 mybox1.volume( ) displays the volume of the box defined by mybox1, and the call to mybox2.volume( ) displays the volume of the box defined by mybox2. Each time volume( ) is invoked, it displays the volume for the specified box. When a method uses an instance variable that is defined by its class, it does so directly, without explicit reference to an object and without use of the dot operator. This is easy to understand if you think about it. A method is always invoked relative to some object of its class. Once this invocation has occurred, the object is known. Thus, within a method, there is no need to specify the object a second time. This means that width, height, and depth inside volume( ) implicitly refer to the copies of those variables found in the object that invokes volume( )
  • #22 While this code works, it is troubling for two reasons. First, it is clumsy and error prone. For example, it would be easy to forget to set a dimension. Second, in well-designed Java programs, instance variables should be accessed only through methods defined by their class. In the future, you can change the behavior of a method, but you can’t change the behavior of an exposed instance variable. variable. Thus, a better approach to setting the dimensions of a box is to create a method that takes the dimensions of a box in its parameters and sets each instance variable appropriately.
  • #23 It can be tedious to initialize all of the variables in a class each time an instance is created. Even when you add convenience methods like setDim( ), it would be simpler and more concise to have all of the setup done at the time the object is first created. Because the requirement for initialization is so common, Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor.
  • #29 Stack class defines two data items, two methods, and a constructor. The stack of integers is held by the array stck. This array is indexed by the variable tos, which always contains the index of the top of the stack. The Stack( ) constructor initializes tos to –1, which indicates an empty stack. The method push( ) puts an item on the stack. To retrieve an item, call pop( ). Since access to the stack is through push( ) and pop( ), the fact that the stack is held in an array is actually not relevant to using the stack. For example, the stack could be held in a more complicated data structure, such as a linked list, yet the interface defined by push( ) and pop( ) would remain the same