0% found this document useful (0 votes)
28 views9 pages

Unit 2-Java

Uploaded by

kunjukukku20
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)
28 views9 pages

Unit 2-Java

Uploaded by

kunjukukku20
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/ 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

}
}

Common questions

Powered by AI

Java supports single-line, multi-line, and Javadoc comments, serving different purposes to enhance code readability and documentation. Single-line comments, marked by //, provide brief annotations or clarify specific lines of code . Multi-line comments, enclosed within /* and */, offer longer explanations or can temporarily disable code blocks during debugging . Javadoc comments, starting with /** and supporting tags like @param, @return, are specialized for generating API documentation, detailing classes, methods, and fields for developers . These diverse comments collectively improve comprehension and facilitate maintenance by clearly explaining code functionality.

In Java, constructors are special methods used to initialize objects; they share the name of the class and are automatically called when an object is created, ensuring proper setup of instance variables . Constructor overloading allows multiple constructors in a class, each with different parameters, providing flexibility in initializing objects. For example, overloaded constructors can initialize objects using default values, single values, or calculated values based on parameters, accommodating diverse instantiation needs . This versatility aids in creating classes that can adapt to different initialization scenarios without altering existing code.

In Java, objects are dynamically allocated memory on the heap using the 'new' keyword, which returns a reference to the object's memory address . This reference is stored in an object reference variable, which does not contain the object itself but a pointer to it. Consequently, when one reference variable is assigned to another, they point to the same object, leading to shared modifications; changes through one reference affect the other . This behavior implies careful management is needed to avoid unintended side effects or references to null if objects are de-allocated or mismanaged.

Java's strong typing ensures that all variables, expressions, and method interactions are strictly type-checked during both compile-time and runtime, preventing type-related errors from existing in the code . This rigorous type-checking enforces compatibility and coherence across the application, reducing bugs that could result from illegal operations, such as mismatched method calls or variable assignments. Compile-time checks avoid execution of faulty code by catching errors early in the development cycle, thereby enhancing software robustness, facilitating earlier debugging, and improving overall code reliability and integrity.

The 'this' keyword in Java refers to the current instance of a class and is essential for distinguishing between class fields and method or constructor parameters with identical names . For instance, in a constructor where parameters have the same name as instance variables, 'this' is used to set the instance variable as shown in the class 'Point': 'this.x = x;' ensures that the instance variable 'x' is assigned the parameter's value, preventing potential errors from name conflicts . Without 'this', it would be unclear whether the assignment targets the parameter or the field.

Class naming conventions in Java require class names to be nouns starting with a capital letter, such as 'MyClass', while method names should be verbs starting with a lowercase letter, using camelCase for multiple words, like 'calculateArea()' . These conventions enhance code readability by clearly distinguishing different elements of the code and maintaining a consistent style. This consistency aids in code maintenance as developers can easily identify component roles, aiding in understanding and modifying the codebase more effectively.

Access modifiers in Java, such as public, protected, private, and package-private, define the visibility scope of classes, methods, and variables, enhancing data encapsulation by restricting access to class members as needed. For instance, 'private' restricts access to within the class, while 'public' allows universal access . Non-access modifiers, like static, final, and abstract, further control the properties and behaviors of code components without altering their visibility. 'Static' associates a method or variable with the class rather than instances, 'final' prevents modification or further inheritance, and 'abstract' requires subclasses to implement methods, thus refining functionality and encapsulation .

In Java, the program file name must exactly match the public class name it contains, which is required by the Java Virtual Machine (JVM) for execution . If a mismatch exists, the Java compiler will generate an error, preventing the program from compiling and running. This requirement ensures a clear mapping between file names and their containing classes, facilitating organized project structures and simplifying navigation, debugging, and collaboration by maintaining predictable file-class relationships.

Java identifiers are names for variables, methods, classes, packages, and user-defined items. They must begin with a letter, underscore (_), or dollar sign ($) and can be followed by letters, digits, underscores, or dollar signs . Identifiers are case-sensitive and cannot be reserved keywords like 'class' or 'int'. There is no length restriction on identifiers, allowing for descriptive, meaningful names that enhance code readability and maintainability . These rules ensure clarity and prevent conflicts within the language's syntax and structure.

Java supports constructor overloading, allowing multiple constructors within a class, each varying by parameter type and count, to initialize objects differently. This ability permits a class like 'MyClass' to have a default constructor for standard initialization, a parameterized constructor for specific values, and another to calculate initial values from multiple inputs . Such versatility enables tailored object instantiation to meet varying application requirements without altering base class structures, enhancing design flexibility, code reuse, and adaptability to evolving software needs, crucial in complex, scalable application environments.

You might also like