[go: up one dir, main page]

0% found this document useful (0 votes)
95 views37 pages

Unit 2 - Part 1 - Classes and Objects

The document provides a comprehensive introduction to classes, objects, and arrays in Java, detailing their definitions, characteristics, and syntax. It covers key concepts such as fields, methods, constructors, and object initialization, along with examples illustrating their usage. Additionally, it discusses methods in Java, including method overloading and overriding, emphasizing their importance in code reusability and modularity.

Uploaded by

shilpa vishwam
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)
95 views37 pages

Unit 2 - Part 1 - Classes and Objects

The document provides a comprehensive introduction to classes, objects, and arrays in Java, detailing their definitions, characteristics, and syntax. It covers key concepts such as fields, methods, constructors, and object initialization, along with examples illustrating their usage. Additionally, it discusses methods in Java, including method overloading and overriding, emphasizing their importance in code reusability and modularity.

Uploaded by

shilpa vishwam
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
You are on page 1/ 37

Unit II - Introduction to Classes and Objects and Arrays

Introduction to Classes and Objects: Defining a Class, Field declaration, method declaration
and definition, instantiating an object of a Class, Accessing class members, declaring
methods with multiple parameters, argument passing, object as a parameter, returning
objects, assigning object reference variables, set methods and get methods,
constructors, this keyword, Constructors, static methods, scope of declaration, method
overloading and Java API packages.

Arrays: declaring and creating arrays in Java, examples using arrays, passing arrays to
methods, multidimensional arrays, variable-length argument lists, using command-line
arguments.

Managing I/O: Streams Byte Streams and Character Streams, Predefined Streams,
Reading console Input, Writing Console Output, Print Writer class.

Case Studies: Demonstrate an interactive Banking/Library management system using


class, objects, array of objects
Introduction to Classes and Objects: Defining a Classes & Objects

What is a Class in Java?


A class is a group of objects that 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 Java class contains:


1. Fields
Variables stated inside a class that indicate the status of objects formed from that class
are called fields, sometimes referred to as instance variables. They specify the data that
will be stored in each class object. Different access modifiers, such as public, private, and
protected, can be applied to fields to regulate their visibility and usability.

2. Methods
Methods are functions defined inside a class that include the actions or behaviors that
objects of that class are capable of performing. These techniques allow the outside
world to function and change the object's state (fields). Additionally, methods can be
void (that is, they return nothing) or have different access modifiers. They can also
return values.
3. Constructors
Constructors are unique methods that are used to initialize class objects. When an
object of the class is created using the new keyword, they are called with the same
name as the class. Constructors can initialize the fields of an object or carry out any
additional setup that's required when an object is created.

4. Blocks
Within a class, Java allows two different kinds of blocks: instance blocks, commonly
referred to as initialization blocks and static blocks. Static blocks, which are usually used
for static initialization, are only executed once when the class is loaded into memory.
Instance blocks can be used to initialize instance variables and are executed each time a
class object is generated.
5. Nested Class and Interface
Java permits the nesting of classes and interfaces inside other classes and interfaces.
The members (fields, methods) of the enclosing class are accessible to nested classes,
which can be static or non-static. Nested interfaces can be used to logically group
related constants and methods together because they are implicitly static.

Java Class Syntax


class <class_name>{
field;
method;
}
object in Java

What is an object in Java?


An object is a real-world entity that has state and behaviour. In
other words, an object is a tangible thing that can be touch and
feel, like a car or chair, etc. The banking system is an example of
an intangible object. Every object has a distinct identity, which is
usually implemented by a unique ID that the JVM uses internally
for identification.
Characteristics of an Object
State: It represents the data (value) of an object.

Behavior: It represents the behavior (functionality) of an object, such as deposit,


withdraw, etc.

Identity: An object's identity is typically implemented via a unique ID. The ID's
value is not visible to the external user; however, it is internally used by the JVM
to identify each object uniquely.

For Example, a Pen is an object. Its name is Reynolds; its color is white, 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 that has state and behavior.
The object is an instance of a class.
Syntax of an Object

<class_name> variable=new <class_name>();


/Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Main{
//defining fields
int id; //field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Main s1=new Main();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Example
//Creating a Student class
class Student{
//declaring fields or instance variables
int id;
String name;
}
//Creating another class which contains the main() method
class Main{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Initializing an Object in Java

There are the following three ways to initialize an object in Java:

By Reference Variable
By Method
By Constructor
Object Initialization through Reference Variable

Initializing an object means storing data in the object. Let's see a simple example
where we are going to initialize the object through a reference variable.
class Student{
int id;
String name;
}
public class Main{
public static void main(String args[]){
//Creating instance of Student class
Student s1=new Student();
//assigning values through reference variable
s1.id=101;
s1.name="Sonoo";
//printing values of s1 object
System.out.println(s1.id+" "+s1.name);
}
}
2) Object Initialization through Method

In this example, we are creating the two objects of Student class and initializing
the value to these objects by invoking the insertRecord method.

Here, we are displaying the state (data) of the objects by invoking the
displayInformation() method.
class Student{
int rollno;
String name;
//Creating a method to insert record
void insertRecord(int r, String n){
rollno=r;
name=n;
}
//creating a method to display information
void displayInformation(){System.out.println(rollno+" "+name);}
}
//Creating a Main class to create objects and call methods
public class Main{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Explanation
The provided Java code includes two classes: Student and Main. The Student class
includes rollno and name as fields, along with the methods insertRecord() and
displayInformation() to initialise and print the respective fields' data. Two Student
objects are created in the main() method of the Main class, and their corresponding
insertRecord() methods are called to set their rollno and name.
3) Object Initialization through a Constructor

The concept of object initialization through a constructor is essential to object-


oriented programming in Java. Special methods inside a class called
constructors are called when an object of that class is created with the new
keyword. They initialise the state of objects by entering initial values in their
fields or carrying out any required setup procedures. The constructor is
automatically invoked upon object instantiation, guaranteeing correct
initialization of the object prior to usage.
class Student {
int id;
String name;
// Constructor with parameters
public Student(int id, String name) {
this.id = id;
this.name = name;
}
// Method to display student information
public void displayInformation() {
System.out.println("Student ID: " + id);
System.out.println("Student Name: " + name);
}
}
public class Main {
public static void main(String[] args) {
// Creating objects of Student class with constructor
Student student1 = new Student(1, "John Doe");
Student student2 = new Student(2, "Jane Smith");
// Displaying information of the objects
student1.displayInformation();
student2.displayInformation();
}
}
Object and Class Example: Rectangle

class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
public class Main{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

Output :
55
45
Methods in Java
What is a Method in Java?
A method is a block of code or collection of statements or a set of code
grouped together to perform a certain task or operation. It is used to achieve
the reusability of code. We write a method once and use it many times. We do
not require to write code again and again. It also provides the easy modification
and readability of code, just by adding or removing a chunk of code. The
method is executed only when we call or invoke it.

The most important method in Java is the main() method.


Why Methods (Key Characteristics)?

Reusability: Methods provides code reusability. Once a method is defined, it can be


called multiple times from various parts of the program.

Modularity: Methods help break down complex problems into smaller, manageable
pieces.

Maintainability: With methods, updating and debugging code becomes easier since
changes in one part of the program do not necessarily impact other parts.

Abstraction: Methods provide a way to encapsulate implementation details, exposing


only the necessary parts to the users.
Method Declaration
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, as we have shown in the following figure.

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.
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.
Naming a Method
While defining a method, remember that the method name must be a verb and start
with a lowercase letter. If the method name has more than two words, the first name
must be a verb followed by adjective or noun. In the multi-word method name, the first
letter of each word must be in uppercase except the first word. For example:

Single-word method name: sum(), area()


Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the
same class, it is known as method overloading.

Types of Method
There are two types of methods in Java:
Predefined Method
User-defined Method
Static Method

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. The best example of a static
method is the main() method.
Example of Static Method
Display.java
public class Display
{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static method.");
}
}
Output: It is an example of a static method.
Method Overloading

Method overloading is a feature in Java that allows multiple methods with the
same name but different parameter lists to exist within the same class. It
enhances the flexibility and readability of the code.
Example

public class PrintUtil {


// Method with one parameter
public void print(String message) {
System.out.println(message);
}
// Overloaded method with two parameters
public void print(String message, int times) {
for (int i = 0; i < times; i++) {
System.out.println(message);
}
}
}
Method Overriding

Method overriding occurs when a subclass provides a specific implementation for a


method that is already defined in its superclass. It is a key aspect of polymorphism in
Java, allowing subclasses to customize or extend the behavior of inherited methods.
Example

class Animal {
// Method to be overridden
public void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
// Overriding method
@Override
public void sound() {
System.out.println("Dog barks");
}
}

You might also like