[go: up one dir, main page]

0% found this document useful (0 votes)
59 views14 pages

OOP Chapter 3

This document discusses object-oriented programming concepts in Java including objects, classes, instantiation, and constructors. [1] An object has state, behavior, and identity while a class is a template for objects and defines their common properties. [2] Instantiation creates an object from a class using the new operator and allocates memory. [3] Constructors initialize an object's fields and can be default or parameterized to set initial values.

Uploaded by

ashagerie asfaw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views14 pages

OOP Chapter 3

This document discusses object-oriented programming concepts in Java including objects, classes, instantiation, and constructors. [1] An object has state, behavior, and identity while a class is a template for objects and defines their common properties. [2] Instantiation creates an object from a class using the new operator and allocates memory. [3] Constructors initialize an object's fields and can be default or parameterized to set initial values.

Uploaded by

ashagerie asfaw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Object Oriented Programming in Java Lecture note

Chapter Three
Objects and Classes
3.1 . object and classes in Java
Object: an entity that has state and behavior. e.g., chair, bike, marker,
pen, table, car, etc. It can be physical or logical (tangible and intangible).
The example of an intangible object is the banking system.
An object has three characteristics:
➢ State: represents the data (value) of an object.
➢ Behavior: represents the behavior (functionality) of an object
such as deposit, withdraw, etc.
➢ Identity: An object identity is typically implemented via a
unique ID. The value of the ID is not visible to the external user. However, it is used internally by the
JVM to identify each object uniquely.
Example: Pen is an object. Its name is Bic; color is Blue, known as its state. It is used to write, so writing is its
behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an
object is the instance(result) of a class.
Object Definitions:
➢ An object is a real-world entity.
➢ An object is a runtime entity.
➢ The object is an entity which has state and behavior.
➢ The object is an instance of a class.

class in Java
A class is a group of objects which have common properties. It is a template or blueprint from which objects
are created. It is a logical entity. It can't be physical.
A class in Java can contain:
➢ Fields
➢ Methods
➢ Constructors
➢ Blocks

1|Page
Object Oriented Programming in Java Lecture note

3.2 . Instantiating and Using Objects


In Java, instantiation mean to call the constructor of a class that creates an instance or object of the type of
that class. In other words, creating an object of the class is called instantiation. It occupies the initial memory
for the object and returns a reference. An object instantiation in Java provides the blueprint for the class.
Use new operator to create a new object
A class defines what fields an object will have when it's created.
Syntax: ClassName objName = new ClassName();
When a new Student object is created, a block of memory is allocated, which is big enough to hold these
three fields -- as well as some extra overhead that all objects have.
Student stud;
stud = new Student(); // Create Student object with new operator.
Or we can write in one line in the following way:
Student stud=new Student ( );
To create a new object, write new followed by the name of the class (called Constructor), followed by
parentheses.
Example to create objects
//Java Program to illustrate the use of Rectangle class which
//has length and width data members
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

2|Page
Object Oriented Programming in Java Lecture note

Accessing Objects
Newly created objects are allocated in the memory. They can be accessed via reference variables (objects).
The objects of the classes are independent. A class is essentially a programmer-defined type. A class is
a reference type, which means that a variable of the class type can reference an instance of the class.
After an object is created, its data can be accessed and its methods invoked using the dot operator (.), also
known as the object member access operator.
Accessing a Data Fields
Syntax: (it is by reference of object).
objectRefVar.dataField;
Example:
circle1.radius; //References the radius in circle1.
Accessing a Methods
Syntax: (it is by reference of object).
objectRefVar.method(arguments);
Example:
circle1.getArea(); //Invokes the getArea method on circle1. Methods are invoked as operations on objects.

3.3 . Constructors and Methods in Java


Java Constructors
 Constructor can be Default and Parameterized
A constructor is a special initialization method that is called automatically whenever an instance of a class is
created. The constructor member method has, by definition, the same name as the corresponding class. The
constructor has no return value specification. The Java run-time system makes sure that the constructor of a
class is called when instantiating an object.
• Automatically invoked when a class instance is created using the new operator
o Has same name as the class
o Has no return type
o Java creates a default constructor if no constructor has been explicitly written for a class
Constructors are used to initialize the data members of the class. If we have data members that must be
initialized, we must have a constructor.

3|Page
Object Oriented Programming in Java Lecture note

A. Default (Non-Parameterized) Constructors


Used to initialize objects using default values, let us look at the following example.
public class Employee{
String empName;
String address;
int id;
public Employee( ) // Default constructor
{
empName = “ ”;
address = “”;
int=0;
}
} //end of class
The constructor Employee() is a default or non-parameterized constructor, because it doesn’t use parameters.
Default constructor is used to initialize the object with default value.

B. Parameterized Constructors
The parameterized constructors can accept values into the constructor that has different parameters in the
constructor. The value would be transferred from the main ( ) method to the constructor either with direct
values or through variables. Parameterized Constructor has parameter list to receive arguments for
populating the instance attributes.

When you create a new instance (a new object) of a class using the new keyword, a constructor for that class
is called. Constructors are used to initialize the instance variables (fields) of an object. Constructors are
similar to methods, but with some important differences.
• A constructor must have the same name as the class itself.
• Constructors do not have a return type – not even void.
• Constructors are invoked using the new operator when an object is created. Constructors play the role
of initializing objects.
• Default constructor. If you don't define a constructor for a class, a default (parameter less)
constructor is automatically created by the compiler. The default constructor calls the default parent
constructor (super( ) and initializes all instance variables to default value (zero for numeric types, null
for object references, and false for Booleans).

4|Page
Object Oriented Programming in Java Lecture note

Example 1: //a class without constructors


public class Circle {
public int x, y; // centre of the circle
public int r; // radius of circle
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r; }
public double area() {
return 3.14 * r * r; }
public static void main(String args[]) {
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+"Area="+area);
System.out.println("Radius="+aCircle.r+"
Circumference ="+circumf);
}}
Example 2: // Write the above code using constructors
public class Circle {
public int x, y; // centre of the circle
public int r; // radius of circle
Circle( )
{ x=0; y=0; r=0; }
Circle(int valx , int valy , int valr)
{ x=valx; y=valy ; r=valr; }
//Methods to return circumference and area
public double circumference( )
{ return 2*3.14*r; }
5|Page
Object Oriented Programming in Java Lecture note

public double area( )


{ return 3.14 * r * r; }
public static void main (String args[]){
Circle c1=new Circle();
System.out.println("The value of x is " + c1.x);
System.out.println("The value of yis "+ c1.y);
System.out.println("The value of r is " + c1.r);
Circle c2=new Circle(4,2,5);
System.out.println("The value of x is " + c2.x);
System.out.println("The value of y is " + c2.y);
System.out.println("The value of r is " + c2.r);
System.out.println("Area of c2 is" +c2.area( ));
System.out.println("Circumference of c2 is "+c2. circumference( ));
}}
Example 3: Default and Parameterized constructor. This example is about a polygon, Cube
public class Cube1 {
int length;
int width;
int height;
public int getVolume() {
return (length *width * height);
}
Cube1( ) {
length = 0;
width = 0;
height = 0;
}
Cube1 (int l, int b, int h) {
length = l;
width = b;
height = h;
}
6|Page
Object Oriented Programming in Java Lecture note

public static void main(String[] args) {


Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1( );
cubeObj2 = new Cube1(10, 10, 10);
System.out.println("Volume of Cube is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube is : " + cubeObj2.getVolume());
}
If such a class requires a default constructor, its implementation must be provided. Any attempt to call the
default constructor will be a compile time error if an explicit default constructor is not provided in such a
case.

class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
7|Page
Object Oriented Programming in Java Lecture note

Java Methods
A Java method is a collection of statements that are grouped together to perform an operation. When you call
the System.out.println method, for example, the system actually executes several statements in order to
display a message on the console. Now you will learn how to create your own methods with or without return
values, invoke a method with or without parameters, overload methods using the same names, and apply
method abstraction in the program design.

Method Declaration and their components


modifier returnType MethodName (Parameter List)
{
// method body
}
The method declaration provides information about method attributes, such as visibility, return-type, name,
and arguments. It has six components that are known as method header.

Method Signature: Every method has a method signature. It is a part of the method declaration. It includes
the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of
the method. Java provides four types of access specifier:
Public: The method is accessible by all classes when we use public specifier in our application.
Private: When we use a private access specifier, the method is accessible only in the classes in which
it is defined.
Protected: When we use protected access specifier, the method is accessible within the same package
or subclasses in a different package.

8|Page
Object Oriented Programming in Java Lecture note

Default: When we do not use any access specifier in the method declaration, Java uses default access
specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to
the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the
method name must be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It
contains the data type and variable name. If the method has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed
within the pair of curly braces.

A. Java Instance Methods


The instance methods are bound to the class instance and perform a set of actions on the data/value given by
the object (instance) variables. It is a non-static method defined in the class. Before calling or invoking the
instance method, it is necessary to create an object of its class.
➢ Instance method are methods which require an object of its class to be created before it can be called.
To invoke an instance method, we have to create an Object of the class in within which it defined.
➢ Instance method(s) belong to the Object of the class not to the class i.e. they can be called after
creating the Object of the class.
➢ Every individual Object created from the class has its own copy of the instance method(s) of that class.

B. Java static methods


A method that has static keyword is known as static method. In other words, a method that belongs to a class
rather than an instance of a class is known as a static method. We can also create a static method by using the
keyword static before the method name.

The main advantage of a static method is that we can call it without creating an object. It can access static data
members and also change the value of it. It is used to create an instance method. It is invoked by using the
class name. We can call a static method by using the ClassName.methodName.
The best example of a static method is the main() method. It is called without creating the object.
➢ A static method belongs to the class rather than the object of a class.
➢ A static method can be invoked without the need for creating an instance of a class.
9|Page
Object Oriented Programming in Java Lecture note

➢ A static method can access static data member and can change the value of it.

Difference between constructor and method in Java


There are many differences between constructors and methods. They are given below.
Java Constructor Java Method
used to initialize the state of an object. used to expose behavior of an object.
must not have return type. must have return type.
invoked implicitly. invoked explicitly.
Java compiler provides a default constructor if you not provided by compiler in any case.
don't have any constructor.
name must be same as the class name. name may or may not be same as class name.

3.4 . Access Modifiers/Specifiers in Java


The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.

1) private access modifier


The private access modifier is accessible only within class.
Example: we have created two classes A and B. A class contains private data member and private method.
We are accessing these private members from outside the class, so there is compile time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class B{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from outside the class.
10 | P a g e
Object Oriented Programming in Java Lecture note

Example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
} }

Note: A class cannot be private or protected except nested class.

2) default access modifier


If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package.
Example: we have created two packages pack and mypack. We are accessing class A from outside its
package, since class A is not public, so it cannot be accessed from outside the package.
//saved by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//saved by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
} }
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.
11 | P a g e
Object Oriented Programming in Java Lecture note

3) protected access modifier


The protected access modifier is accessible within package and outside the package but through inheritance
only.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied
on the class.
Example: we have created two packages pack and mypack. The A class of pack package is public, so can
be accessed from outside the package. But msg method of this package is declared as protected, so it can be
accessed from outside the class only through inheritance.
//saved by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//saved by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}

4) public access modifier


The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example of public access modifier
//saved by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

12 | P a g e
Object Oriented Programming in Java Lecture note

//saved by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Understanding all Java access modifiers


Let's understand the access modifiers by a simple table (Y=Yes and N=No).

Can be Accessed

Access within within outside package


outside package
Modifier class package by subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Source file declaration rules:


The rules are essential when declaring classes, import statements and package statements in a source file.
❖ There can be only one public class per source file.
❖ A source file can have multiple nonpublic classes.
❖ The public class name should be the name of the source file as well which should be appended by
.java at the end.
For example: The class name is public class Employee{} Then the source file should be as
Employee.java.

13 | P a g e
Object Oriented Programming in Java Lecture note

❖ If the class is defined inside a package, then the package statement should be the first statement in the
source file.
❖ If import statements are present then they must be written between the package statement and the class
declaration.
❖ If there are no package statements then the import statement should be the first line in the source file.
Import and package statements will imply to all the classes present in the source file. It is not possible to
declare different import and/or package statements to different classes in the source file.

14 | P a g e

You might also like