0% found this document useful (0 votes)
18 views

Unit 2-Java

Uploaded by

kunjukukku20
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Unit 2-Java

Uploaded by

kunjukukku20
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Unit 2: Classes and Objects

basic rules of Java programming:

Class Naming: Class names should be nouns and start with a capital letter (e.g., MyClass).

Method Naming: Method names should be verbs and start with a lowercase letter, if multiple
words are used to form the name of the method, then each iiner word’s first letter should be
upper case/(e.g., calculateArea()).

Program File Name: Name of The program file shold exactly match the class name, if multiple
class available in single file, File name should match with the class name including main
method.

Java Identfiers
In Java, an identifier is a name given to a variable, method, class, package, or other user-defined
item.
basic rules for Java identifiers:
✓ Must begin with a letter, underscore (_), or dollar sign ($). It cannot begin with a digit.
✓ Subsequent characters can be letters, digits, underscores, or dollar signs. No other
characters are allowed.
✓ Java identifiers are case-sensitive. For example, myVariable and MyVariable are treated
as different identifiers.
✓ Cannot be a reserved keyword. Java has reserved keywords that have specific meanings
in the language and cannot be used as identifiers. Examples of keywords include class,
int, public, static, etc.
✓ No length limit. Java identifiers can be of any length.

Java modifiers
In Java, modifiers are keywords that define the access level, behavior, and properties of classes,
methods, variables, and other program elements.

Access Modifiers:

public: The element is accessible from any other class.

protected: The element is accessible within its own package and by subclasses.

private: The element is accessible only within its own class.

(Default/Package-private): The element is accessible only within its own package.

Non-Access Modifiers:

static: The element belongs to the class rather than instances of the class.

final: The element's value cannot be changed. For variables, it indicates a constant value. For
methods, it indicates the method cannot be overridden. For classes, it indicates the class cannot
be subclassed.
abstract: The element does not have an implementation. For methods, it indicates the method
must be implemented by a subclass. For classes, it indicates the class cannot be instantiated
directly and must be subclassed.
synchronized: The element is thread-safe and can only be accessed by one thread at a time.

volatile: The variable may be modified asynchronously (by different threads), and its value
should never be cached.

Java Comments
In Java, comments are used to provide information about the code to developers or to
temporarily disable certain parts of the code.
Java supports three types of comments:

Single-Line Comments: Single-line comments begin with // and continue until the end of the
line. They are commonly used for short descriptions or annotations.

Multi-Line Comments: Multi-line comments begin with /* and end with */. They can span
multiple lines and are typically used for longer descriptions or for temporarily disabling blocks
of code.

Javadoc Comments: Javadoc comments are a special type of comment used to generate
documentation for classes, interfaces, methods, and fields. They begin with /** and end with
*/. Javadoc comments support special tags such as @param, @return, @throws, etc., which are
used to provide additional information about the code that can be processed by documentation
generation tools.

Java keywords
In Java, keywords are reserved words that have predefined meanings and cannot be used for
naming variables, classes, methods, or any other identifiers. These keywords serve various
purposes in Java, such as defining classes, control flow, data types, and access modifiers.

Java is Strongly typed language


Java is considered a strongly typed language due to its strict enforcement of data type rules
during compile-time and runtime.

Compile-Time Type Checking:


Java's compiler verifies the types of variables, expressions, and method arguments during
compilation. If there are any type mismatches or violations, the compiler generates errors,
preventing the execution of the program until the issues are resolved.

Type Safety:
Java ensures type safety by disallowing operations that would result in incompatible types or
potential data loss.
Class in Java
In Java, a class is a blueprint or template for creating objects.It is a user defined data type.
It defines the properties (attributes) and behaviors (methods) that objects of that class will
have.
When you define a class, you declare its exact form and nature. You do this by specifying the
data that it contains and the code that operates on that data.

A class is declared by use of the class keyword.

class ClassName {
// Fields (attributes)
dataType fieldName1;
dataType fieldName2;
// ...

// Methods
returnType methodName1(parameters) {
// Method body
}

returnType methodName2(parameters) {
// Method body
}
// ...
}

Fields (Attributes): Inside the class body, you can declare fields to represent the attributes of
objects of this class. Each field declaration includes the data type of the field followed by the
field name.

instance variable
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.

Methods: Inside the class body, you can define methods to define the behavior of objects of
this class. Each method declaration includes the return type (or void if the method does not
return anything), method name, and parameter list. Method bodies contain the executable code
for performing specific actions.

return type methodName1(parameters)


{
// Method body
}

return 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.

The data/fields, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class are
called members of the class.
class Box
{
//instance variable
double width;
double height;
double depth;
// display volume of a box
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class DemoBox
{
public static void main(String args[])
{
Box b1 = new Box();
// assign values to mybox1's instance variables
b1.width = 10;
b1.height = 20;
b1.depth = 15;

// display volume of first box


b1.volume();
}
}

Declaring Objects / Steps to create Object

Creating objects of a class is a two-step process.


Step 1 : Create reference variable
First, you must declare a variable of the class type. This variable does not define an object.
Instead, it is simply a variable that can refer to an object.
Step 2 : Allocate memory for object
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. The new operator dynamically allocates (that is,
allocates at run time) memory for an object and returns a reference to it. This reference is, more
or less, the address in memory of the object allocated by new. This reference is then stored in
the variable.

Box b1; // declare reference to object


b1 = new Box(); // allocate a Box object

The first line declares b1 as a reference to an object of type Box. After this line executes,
b1 contains the value null, which indicates that it does not yet point to an actual object.

The next line allocates an actual object and assigns a reference to it to b1. After the second line
executes, you can use b1 as if it were a Box object. But in reality, b1 simply holds the memory
address of the actual Box object.

Box b1;

b1

b1 = new Box();

b1

Assigning Object Reference Variables


Object reference variables act differently than you might expect when an assignment takes
place.

Box b1 = new Box();


Box b2 = b1;

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.
When you assign one object reference variable to another object reference variable,
you are not creating a copy of the object, you are only making a copy of the reference.

Constructor in java
In Java, a constructor is a special type of method that is used to initialize objects of a class.
It 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 immediately after the object is created,
before the new operator completes.
Constructors have the same name as the class and do not have a return type, not even void.
Constructors are primarily used to initialize instance variables or perform any necessary setup
operations.

class Box
{
double width;
double height;
double depth;

// This is the constructor for Box.


Box()
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
double volume()
{
return width * height * depth;
}
}
class DemoBox
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
}
}

Constructor overloading
Constructor overloading in Java allows a class to have multiple constructors with different
parameter lists. Each constructor can initialize the object in a different way based on the
parameters provided. This provides flexibility when creating objects of the class, as different
constructors can be used depending on the specific requirements.

Constructor overloading is useful when you want to provide multiple ways to initialize objects
of a class, based on different combinations of parameters.

class MyClass
{
private int value;

// Constructor without parameters


MyClass()
{
value = 0; // Default initialization
}

// Constructor with a single parameter


MyClass(int value)
{
this.value = value;
}

// Constructor with two parameters


MyClass(int value1, int value2)
{
this.value = value1 + value2;
}

// Getter method to retrieve the value


public int getValue() {
return value;
}
}
class DemoMyClass
{
public stativ coid main(String args[])
{
MyClass o1 = new MyClass(); // Calls the default constructor
MyClass o2 = new MyClass(10); // Calls the constructor with a one parameter
MyClass 3 = new MyClass(20, 30); // Calls the constructor with two parameters
}
}
In this example, the class MyClass has three constructors:

✓ A default constructor MyClass() that initializes the value field to 0.


✓ A constructor MyClass(int value) that initializes the value field with the provided
value.
✓ Another constructor MyClass(int value1, int value2) that initializes the value field
with the sum of two provided values.

this keyword in java


In Java, the this keyword is a reference to the current object within an instance method or
constructor. It can be used to refer to the current instance's fields, methods, or constructors,
allowing for disambiguation between instance variables and parameters with the same name

Accessing Instance Variables:


When a method or constructor parameter has the same name as an instance variable, the this
keyword can be used to refer to the instance variable.
class Point
{
private int x,y;

public MyClass(int x,int y)


{
this.x = x; // 'this' refers to the instance variable
this.y = y;
}

public void setPoint(int x,int y)


{
this.x = x; // 'this' refers to the instance variable
this.y = y;

}
}

Returning Current Object:


Methods can return the current object (this) to enable method chaining.
class Point
{
private int x,y;

public MyClass(int x,int y)


{
this.x = x; // 'this' refers to the instance variable
this.y = y;
}

public Point add2()


{
this.x = x +2;
this.y = y+2;
return this; // 'this' refers to the current object

}
}

You might also like