0% found this document useful (0 votes)
4 views42 pages

Java OOP: Classes, Methods, Constructors

Uploaded by

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

Java OOP: Classes, Methods, Constructors

Uploaded by

Sourav Shekhawat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

MODULE - 2

Classes, objects, methods and Constructors


[Lecture:6 & Practical:5]

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 1


L1 - Content
• Object Oriented Concepts
• Classes and Objects
• Adding Methods to the class
• Adding Parameter to the methods
• Activity

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 2


Object Oriented Concepts
Object Encaps
ulation

Object Data
CLASS Oriented Abstrac
Concepts tion

Inheritance Polymor
phism

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 3


Object Oriented Concepts
 Class - is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.
 Object - is a basic unit of Object Oriented Programming and represents the real life
entities. A typical Java program creates many objects, which interact by invoking
methods.
 Data Abstraction - is the property by virtue of which only the essential details are
displayed to the user. The trivial or the non-essentials units are not displayed to the
user. Ex: A car is viewed as a car rather than its individual components.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 4


Object Oriented Concepts
 Encapsulation - It is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates. Another way to think
about encapsulation is, it is a protective shield that prevents the data from being accessed
by the code outside this shield.
 Polymorphism- It refers to the ability of OOPs programming languages to differentiate
between entities with the same name efficiently. This is done by Java with the help of the
signature and declaration of these entities.
 Inheritance - is an important pillar of OOP(Object Oriented Programming). It is the
mechanism in java by which one class is allow to inherit the features(fields and methods)
of another class.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 5


Encapsulation Classes and Objects

• A Java program consists of one or more classes


• A class is an abstract description of objects
• Here is an example class:
• class Dog { ...description of a dog goes here... }
• Here are some objects of that class:

Syntax to declare a class:


class <class_name>
{
field;
method;
}

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 6


Classes, Objects and Methods Classes contain data definitions
• Classes describe the data held by each of its objects
• Example: Data usually goes first in a class
• class Dog {
String name;
int age;
...rest of the class...
}
• A class may describe any number of objects
• Examples: "Fido", 3; "Rover", 5; "Spot", 3;
• A class may describe a single object, or even no objects at all

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 7


Activity
Q1. Mr. John has joined a Company as Database Administrator and his major role is to
maintain the Employee database which includes Employee Id, Name, Age and Salary.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 8


Classes, Objects and Methods Classes contain methods
• A class may contain methods that describe the behavior of objects
• A method must be declared within a class. It is defined with the name of the method,
followed by parentheses ().
• Java provides some pre-defined methods, such as [Link](), but you can also
create your own methods to perform certain actions:
• When we ask a particular Dog to bark, it says “Woof!”
• Only Dog objects can bark; the class Dog cannot bark
Example:
class Dog {
Methods usually go after the ...
data void bark() {
[Link]("Woof!");
}
}

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 9


Classes, Objects and Methods Methods contain statements and Parameters
• A statement causes the object to do something
• (A better word would be “command”—but it isn’t)
• Example:
[Link]("Woof!");
• This causes the particular Dog to “print” (actually, display on the screen) the characters
Woof!
Example:
• Data described in a class exists in all objects of that class void wakeTheNeighbors( ) {
• Example: Every Dog has its own name and age int i = 50; // i is a temporary variable
• A method may contain local temporary data that exists only while (i > 0) {
until the method finishes(either as parameter or with in its bark( );
body) i = i – 1;
}
}

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 10


Classes, Objects and Methods

Parameters
• Actual Parameters
Actual Parameters

• Formal Parameters

Formal Parameters

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 11


Activity
Q1. Mr. John has joined a Company as Database Administrator and his major role is to
maintain the Employee database which includes Employee Id, Name, Age and Salary. Help
Mr. John to read/store the records and retrieve all the records which he has stored.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 12


L2 - Content
• Method overloading
• Activity on Method overloading
• Access Specifiers
• Adding Constructors to the class
• Activity on Constructors

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 13


Classes, Objects and Methods Methods can be overloaded
• Method overloading is a feature of Java in which a class has more than one method of
the same name and their parameters are different
Example class CalculateSquare {
void square() {
[Link]("No Parameter Method Called");
}
Overloading int square( int number ) {
int square = number * number;
[Link]("Method with Integer Argument Called:"+square);
}
float square( float number ) {
float square = number * number;
[Link]("Method with float Argument Called:"+square);
}
}

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 14


Activity
Q1. Mr. John has joined a Company as Database Administrator and his major role is to
maintain the Employee database which includes Employee Id, Name, Age and Salary. He
has given a freedom to read/store the data in the database as shown below:
1. Read all the data by taking values from the user.
2. Read only Employee Id from the user and store some default values as he likes to name,
age and Salary.
3. Read Employee Id and Name from the user and store some default values as he likes to
age and Salary. Help Mr. John to store the records and retrieve all the records which he
has stored.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 15


PACKAGE 1
Classes, Objects and Methods Class two
Subclass
Class one{
ACESS SPECIFIERS ACESS SPECIFIERS int d; d a b c
private: int a;
The access level of a public modifier is everywhere. It can public: int b;
Class three
be accessed from within the class, outside the class, within protected: int c;
PUBLIC
the package and outside the package. } d a b c
The access level of a protected modifier is within the
package and outside the package through child class. If
PROTECTED you do not make the child class, it cannot be accessed from
outside the package.
PACKAGE 2
The access level of a private modifier is only within the Class four
PRIVATE class. It cannot be accessed from outside the class. Subclass
The access level of a default modifier is only within the
d a b c
DEFAULT package. It cannot be accessed from outside the package.
If you do not specify any access level, it will be the default. Class five

d a b c

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 16


Classes, Objects and Methods Classes can contain constructors

• In Java, a constructor is a block of codes similar to the method.


• It is called when an instance of the class is created.
• At the time of calling constructor, memory for the object is allocated in the memory.
• Every time an object is created using the new() keyword, at least one constructor is called.
• If you don’t write a constructor, Java defines one for you (behind the scenes), i.e. It calls a
default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
• You can write your own constructors

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 17


Classes, Objects and Methods Classes can contain constructors
 Rules for creating Java constructor
• Constructor name must be the same as its class name
• A Constructor must have no explicit return type
 Types of constructors
• Default constructor (no-arg constructor)
Example: class Dog {
• Parameterized constructor String name;
int age;
(This part is the constructor) Dog(String n, int a) {
name = n;
age = a;
}
}

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 18


Activity
Q1. Mr. John has joined a Company as Database Administrator and his major role is to
maintain the Employee database which includes Employee Id, Name, Age and Salary. He
also been permitted to generate some default values to the Employee data fields before
adding employee records to the database. Help Mr. John to store the records and retrieve all
the records which he has stored.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 19


L3 - Content
• Constructor overloading
• Activity on Constructor overloading
• Review of Program structure
• Complete program demonstration

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 20


Classes, Objects and Methods Constructors can be overloaded
Example:
• Constructor overloading in Java is a technique class Student5 {
of having more than one constructor with int id;
different parameter lists. String name;
int age;
• They are arranged in a way that each Student5(int i, String n) {
constructor performs a different task. id = i;
Overloading
• They are differentiated by the compiler by the name = n;
}
number of parameters in the list and their Student5(int i, String n, int a) {
types. id = i;
• A constructor is just like a method but without name = n;
age=a;
return type. It can also be overloaded like Java
}
methods. void display() {
[Link](id+" "+name+" "+age);
} }

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 21


Activity
Q1. Mr. John has joined a Company as Database Administrator and his major role is to
maintain the Employee database which includes Employee Id, Name, Age and Salary. He
also been constrained to generate some default values to the Employee data fields before
adding employee records to the database in the following fashion:
1. With default values as EmpId=123, Name=“PC-06”, Age=1 and Salary=20000.00.
2. With default values taken from user as parameters.
3. By copying already created employee record.
Help Mr. John to store the records and retrieve all the records which he has stored.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 22


Classes, Objects and Methods Diagram of program structure
Program
File File File
Class
Variables

Constructors Variables File


Statements

Methods Variables • A program consists of


Statements one or more classes
• Typically, each class is
in a separate .java file

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 23


Classes, Objects and Methods A complete program
 class Dog {  void wakeTheNeighbors( ) {
String name; int i = 50;
int age; while (i > 0) {
bark( );
Dog(String n, int a) { i = i – 1;
name = n; }
age = a; }
}
public static void main(String[ ] args) {
void bark() {  //Instantiate an object
[Link]("Woof!");  // Access the Members of Class
}
}
 } // ends the class

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 24


L4 - Content
• Objects Creation/Instantiation
• Accessing the Members of the class using object reference
• Classes and objects summary
• Why to use This keyword - Problem statement

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 25


Classes, Objects and Methods Object Instantiation
• Declaration  public static void main(String[ ] args) {
Declaring a variable that associate a variable name with  //Instantiate an object
an object type.  // Access the Members of Class
}
Ex: Dog D1;  } // ends the class
• Instantiation
The new keyword is a Java operator that creates the  public static void main(String[ ] args) {
object.
Dog fido = new Dog("Fido", 5);
Ex: Dog D1=new Dog();
// Access the Members of Class
• Initialization
}
The new operator is followed by a call to a constructor,
which initializes the new object.  } // ends the class
Ex: Dog D1=new Dog(“Fido”,5); Syntax:
 Classname ObjectName=new Constructor(parameters);

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 26


Classes, Objects and Methods Accessing Members through objects
 public static void main(String[ ] args) {
• Once object is created, we want to use it for something
 //Instantiate an object
like we may need to use the value of one of its fields,  // Access the Members of Class
}
change one of its fields, or call one of its methods to  } // ends the class
perform an action.
 public static void main(String[ ] args) {
• Code that is outside the object's class must use an object
Dog fido = new Dog("Fido", 5);
reference or expression, followed by the dot (.) operator,
[Link]();
followed by a simple field name, as in: }
 } // ends the class

ObjectName . Members(fields) of the class;

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 27


Classes, Objects and Methods

Class Object
It is Conceptual & Independent Entity It is physical(having existence) and dependent Entity

It is a Blue print to object. Without Class object can’t be created


It consists of Attributes and Behaviors It is a instance of Attributes and Behaviors defined for a
Class

Programmatically it is a user defined Data Programmatically it is a variable to a class type data type
type.
E. g : Student, Employee E. g: amit as student, ankit as Employee

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 28


this keyword Problem statement
• Check is it possible to use the local and instance class Dog {
variable with same name or not in the given String name;
example. int age;
• Problem associated with this is called “Instance
Dog(String name, int age) {
variable Hiding”. name = name;
• Reason is, the local or formal parameter hides the age = age;
meaning of instance variable thus causes compiler to }
be in panic mode.
• The Solution to this problem is the use of this void bark() {
[Link]("Woof!");
keyword. }

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 29


L5 - Content
• This keyword
• Activity on this keyword
• Static keyword
• Activity on static keyword

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 30


this keyword Solution

• this is the java keyword. class Dog {


String name;
• This keyword always refers to the current object on int age;

which the method is called. Dog(String name, int age) {


[Link] = name;
 public static void main(String[ ] args) { Current object [Link] = age;
}
Dog fido = new Dog("Fido", 5);
void bark() {
 [Link](); [Link]("Woof!");
}
}

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 31


Activity
Q1. Mr. John has joined a Company as Database Administrator and his major role is to
maintain the Employee database which includes Employee Id, Name, Age and Salary. Help
Mr. John to store the records and retrieve all the records which he has stored by writing a
java program?
Modify the above program using “this keyword”

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 32


static keyword
• The static keyword in Java is used for memory management mainly.
• We can apply static keyword with variables, methods, blocks and nested classes.
• The static keyword belongs to the class than an instance of the class.
The static can be:
Variable (also known as a class variable)
• If you declare any variable as static, it is known as a static variable.
• The static variable can be used to refer to the common property of all objects (which is not unique
for each object), for example, the company name of employees, college name of students, etc.
• The static variable gets memory only once in the class area at the time of class loading.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 33


Java static keyword
The static can be:
 Block(also known as a class method)
• A static block (also called static clause) that can be used for static initializations of a class
• static block and static variables are executed in order they are present in a program
• static blocks are automatically called as soon as class is loaded in memory and there is nothing to
do as we have to in case of calling methods and constructors inside main()
 Method (also known as a class method)
• If you apply static keyword with any method, it is known as static method.
• 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.
• A static method can access static data member and can change the value of it.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 34


Activity

Q1. Mr. John has joined a Company as Database Administrator and his major role is to
maintain the Employee database which includes Employee Id, Name, Age and Salary.
Help Mr. John to display the “total salary expenditure” required for all the employees of
the company in a month.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 35


L6 - Content
• Nested class
• Static Nested Class
• Non Static Nested Class/Inner class

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 36


Nested Class
Nested Class

Static Nested Class Inner Class

Non-Static Anonymous Local Inner


Inner Class Inner Class Class

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 37


class Outer
Nested Class {
//instance variable
int x=20;
//static variable
static int y=20;
Since non-static members and inner
class both are strongly associated //inner class
with outer class object. Without the class inner Since static members and static
object of outer class, non-static nested class both are not strongly
{
members and inner class does not associated with outer class object.
} Without the object of outer class,
exists.
static members and static nested
//static nested class
class can exists.
static class nested
{
}
}

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 38


Nested Class
class Outer Outer class/Top-level class
{
static members
Both static and non-static members of a static nested non-static members
class can access static members of its outer class.
static nested class static class Nested A normal inner class can
access any members of its
cannot have non static {
outer class, regardless of their
members. static members access modifiers.
non-static members
} A non-static
class Inner nested class
A normal inner class can cannot have static
{
access static members of any members.
static nested classes within the
non-static members
same outer class }
}

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 39


Nested Class Comparison

[Link] Normal/Regular inner class Static nested class

Without an outer class object existing, there cannot


Without an outer class object existing, there may be a static
be an inner class object. That is, the inner class
1. nested class object. That is, static nested class object is not
object is always associated with the outer class
associated with the outer class object.
object.

Inside normal/regular inner class, static members


2. Inside static nested class, static members can be declared.
can’t be declared.

As main() method can’t be declared, regular inner


As main() method can be declared, the static nested class
3. class can’t be invoked directly from the command
can be invoked directly from the command prompt.
prompt.

Both static and non static members of outer class Only a static member of outer class can be accessed
4.
can be accessed directly. directly.

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 40


Nested Class Example
Inner class

Static class

Compilation Error

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 41


Module – 2 Completed

Mr. R C Ravindranath, Asst. Prof, SOE-CSE 42

You might also like