03 Chapter Three - Objects and Classe
03 Chapter Three - Objects and Classe
OBJECTS AND
CLASSES
OUTLINE
Object and Class
Creating object
Instantiating and using object
Instance fields
Constructor and Methods
Access Modifier
Encapsulation
CLASS
class is the fundamental that paves the way for object-oriented
programming
class is a group of objects which have common properties
class is a blueprint for creating objects (instances)
It defines the state and behaviors (attributes and methods) that
objects of that class will have
It is a template or blueprint from which individual objects are
created.
CONT …
It is a user-defined data type that can be accessed and
used by creating an instance of that class.
It has its own data members and member functions.
Both member functions and data members are found
in classes.
The data members inside the class are manipulated
using these member functions.
OBJECT
Objects are key to understanding object-oriented technology.
It can be physical or logical (tangible and intangible).
Examples of real-world objects: your cat, your desk, your
television set, your bicycle, laptop, dog, car etc.
Real world object has two characteristics:
State: represents the data (value) of an object.
Behavior: represents the behavior (functionality) of an object.
Object is an instance (result)of a class
SAMPLE PROGRAM- CLASS AND OBJECT
this.color = c;
}
// more code goes here
Public static void main(String args []){
Car vanCar = new Car(); // create object1
Car sportCar = new Car(); // create object2
vanCar.setSize(6);
vanCar.setColor(“blue”); assigning value for object
sportCar.setSize(6); sportCar.setColor(“Greye”);
}
DECLARING CLASS
All classes must be defined by a class declaration that provides the name for the class
and the body of the class.
public keyword indicates that this class is available for use by other classes.
Although it is optional,
You can use any identifier you want to name a class but the following three
If the class name consists of more than one word, begin each word with capital.
Classes create objects, and nouns are the words you use to
Avoid using the name of a Java API class. This is not must, but
if you create a class that has the same name as a Java API class,
tell your class and the API class with the same name apart.
INSTANCE VARIABLE IN JAVA
is created inside the class but outside the method, constructors or any block.
In most classes, the instance variables are acted upon and accessed by the
methods defined for that class.
Thus, it is the methods that determine how a class’ data can be used.
Second, you must acquire an actual, physical copy of the object and assign it to that
variable.
You can do this using the new operator.
INSTANTIATING OBJECTS (2)
It can be rewritten like this to show each step more clearly:
After this line executes, mybox contains the value null, which indicates that it does
not yet point to an actual object.
Any attempt to use mybox at this point will result in a compile-time error.
ASSIGNING OBJECT REFERENCE
VARIABLES
Object reference variables act differently than you might expect when
an assignment takes place.
Box b2 = b1;
That is, you might think that b1 and b2 refer to separate and distinct
objects.
Instead, after this fragment executes, b1 and b2 will both refer to the
same object.
Thus, any changes made to the object through b2 will affect the
Private: methods, variable and constructor can only be accessed within the
declared class.
Access class, variable, method in same package but not from outside.
ACCESS MODIFIERS (2)
The following table shows the access to members permitted by
each modifier.
EXAMPLE
class Rectangle {
}
DATA MEMBERS
Fields are defined the same as any other Java variable, but can have a modifier that
specifies whether the field is public, protected or private.
If the data member/field specifies the public keyword, then it is visible outside of
the class.
If you don’t want the field to be visible outside of the class, use the private keyword
instead.
The value of a final field can’t be changed once it has been initialized.
OTHER MODIFIERS
Abstract: this declaration can apply to classes or methods and indicates that
the class cannot be directly instantiated.
WHAT IS METHOD?
A method is a collection of statements that are grouped together to perform an
operation.
In another way, method is a block of statements that has a name and can be
executed by calling it from some other place in your program.
You may not realize it, but you’re already very experienced with using
methods.
For e.g, to print text to the console, you use the println() or print() methods
To get an integer from the user, you use the nextInt() method.
In all methods, the main method is a method that contains the
statements that are executed when you run your program.
// body of method
Modifier-:
Defines access type of the method i.e. from where it can be accessed in
your application.
Access modifiers used with methods are: public, private, protected and
default.
DEFINING METHODS (2)
The return type: The data type of the value returned by the method or void if
does not return a value.
Parameter list: Comma separated list of the input parameters are defined,
preceded with their data type, within the enclosed parenthesis.
If there are no parameters, you must use empty parentheses ().
The method gets data to process from the parameters during execution .
Here is the source code of the above defined method called max().
The return type and exceptions are not considered as part of it.
max(int x, int y)
HOW TO NAME A METHOD?
A method name is typically a single word that should be a verb in
lowercase or multi-word that begins with a verb in lowercase followed
by adjective, noun…..
After the first word, first letter of each word should be capitalized. For
example, findSum, computeMax, setX and getX
but sometime a method might have the same name as other method
names within the same class as method overloading is allowed in java.
CALLING METHODS
Methods don't do anything until you call them into action i.e. they will not
be executed until called.
The code that calls the method contains the name of the method to be
executed and any needed data that the receiving method requires
(argument).
The required data for a method are specified in the method's parameter list.
HOW METHODS ARE CALLED ?
There are two ways in which a method is called i.e., method returns a
value or returning nothing (no return value).
This called method then returns control to the caller in two conditions, when :
method
}
RETURNING VALUES
The real utility of methods comes when they can perform some task such as a
calculation, and then return the value of that calculation to the calling
method,
so the calling method can do something with the value.
To create a method that returns a value, you need two steps:
i. When defining the method, simply indicate the type of the value returned by
the method on the method declaration.
The return type of a method is simply any of Java’s primitive data types
Methods that do not return a value use a return type of void instead of data
type.
ii. Use the return statement inside the method to return the value after
computation.
RETURNING VALUES (2)
When you specify a return type other than void in a method declaration,
the body of the method must include a return statement that specifies the
value to be returned.
return value/expression;
The expression must evaluate to a value that’s the same type as the type
listed in the method declaration.
In other words, if the method returns an int, the expression in the return
statement must evaluate to an int.
PARAMETER PASSING
The method can then use the parameter as if it were a local variable initialized with
the value.
You can use any data type for a parameter of a method or a constructor.
This includes primitive data types, such as doubles, floats, and integers, and
reference data types, such as objects and arrays.
Arguments are the actual values that are passed in when the method is invoked.
When you invoke a method, the arguments used must match the declaration's
parameters in type and order.
PARAMETER DECLARATION
For each parameter used by the method, you list the parameter
data type followed by the parameter name.
If you need more than one parameter, you separate them with
commas.
PARAMETER DECLARATION….
The syntax for parameter declaration:
return-type method-name (datatype1 parameter1, datatype2 parameter2,
datatype3 parameter3,…) {
//method body
The key with pass by value is that the method will not receive the actual
variable that is being passed – but just a copy of the value being stored inside
the variable.
A. PASSING PRIMITIVE TYPES – PASS
BY VALUE
In Java, primitive arguments, such as int, double, float, byte, etc,
This means that any changes to the values of the parameters exist
When the method returns, the parameters are gone and any
So objects are still passed by value in Java, just like everything
B. PASSING REFERENCE DATA TYPES –
PASS BY VALUE?..
This means that when the method returns, the passed-in reference
For Example:
class Box{
// A Constructor
Box() {}
}
// We can create an object of the above class
// using the below statement. This statement calls above constructor.
Box obj = new Box();}
RULES FOR WRITING CONSTRUCTOR
Constructors have no return type, not even void.
This is because the implicit return type of a class’s constructor is the class type itself.
It is the constructor’s job to initialize the internal state of an object so that the
immediately.
i. default constructor,
Once it gets its object argument, creates a copy of it and create new
object.
DIFFERENCE BETWEEN CONSTRUCTOR AND
METHOD IN JAVA
i.e. Using this you can refer the members of a class such as
constructors, variables and methods as shown in fig below:
ACCESSING MEMBERS
To access data members and methods of classes using objects, we use the dot(.)
operator.
This is the only way to access members of class since Java does not support pointers.
objectname.method();
System.out.println(b1.width);
System.out.println(b1.height);
b1.calcArea();
System.out.println(b1.area);
STATIC MEMBERS
In classes, it is possible to create a member (method or field) that can
To create such a member, precede its declaration with the keyword
static.
objects of its class are created, and without reference to any object.
STATIC MEMBERS(2)
The most common example of a static member is main( ).
Instead, all instances of the class share the same static variable.
automatically.
It is automatically done by the garbage collector (a part of JVM) so we don't need to make
extra efforts.
HOW CAN AN OBJECT BE
UNREFERENCED?
There are many ways:
By nulling the reference
Employee e=new Employee();
e=null;
In Java, just like methods, variables of a class too can have another class as its member. i.e.
Writing a class within another is allowed in Java.
The class written within is called the nested class, and the class that holds the inner class is
called the outer class.
The scope of a nested class is bounded by the scope of its enclosing class.
For example, if class B is defined within class A, then B is known to A, but not outside of A.
A nested class has access to the members, including private members, of the class in
which it is nested.
However, the enclosing class does not have access to the members of the nested class.
General Syntax of Nested Classes
Note:
Non-static nested classes − these are the non-static members of a class.
We know a class cannot be associated with the access modifier private,
but if we have the class as a member of other class, then the inner class
can be made private.
Inner classes are of three types depending on how and where you
define them. They are −
i) Inner Class ii) Method-local Inner Class iii) Anonymous Inner Class
I. INNER CLASS
The most important type of nested class is the inner class.
It has access to all of the variables and methods of its outer class and may
refer to them directly in the same way that other non-static members of
the outer class do.
Thus, an inner class is fully within the scope of its enclosing class.
Creating an inner class is quite simple. You just need to write a class
within a class.
Unlike a class, an inner class can be private and once you declare an
inner class private, it cannot be accessed from an object outside the class.
DECLARING INNER CLASSES
class outerClassName
{
//body of outer class
[private|protected|public] class innerClassName
{
// body of inner class
}
}
EXAMPLE #1: INNER CLASS
class Outer_Demo { public class My_class {
int num; public static void main(String args[]) {
// inner class
// Instantiating the outer class
private class Inner_Demo {
Outer_Demo outer = new Outer_Demo();
public void print() {
System.out.println("This is an inner class"); // Accessing the display_Inner() method.
} outer.display_Inner();
} }
// Accessing the inner class from the method within
}
void display_Inner() {
Inner_Demo inner = new Inner_Demo();
inner.print(); Output: This is an inner
}
class.
}
HOW INNER CLASS IS WORKS?
The outer class first has to create instance of the inner class before
using it.
display_Inner() is the method inside which we are instantiating the inner class, and
this method is invoked from the main method.
II. METHOD-LOCAL INNER CLASS
In Java, we can write a class within a method and this will be a
local type.