Unit-3 Class and objects
3.1 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.
Everything in Java is associated with classes and objects, along with its attributes and methods. A class is container for variable, methods, constructor etc. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.
A class in Java can contain:
- Fields
- Methods
- Constructors
- Blocks
- Nested class and interface
Syntax to declare a
class:
1.
class <class_name>{
2.
field;
3.
method;
4.
}
3.2 Object in Java
A Java object is a member (also
called an instance) of a Java class. Each object has an identity, a behavior
and a state. In Java, an object is
created from a class.
To create an object of Main, specify the class name, followed by the object name, and use the
keyword new:
Example
Create an object called "myObj" and print the value of x:
public class Class_name {
int x = 5;
public static void main(String[] args) {
Class_name myObj = new Class_name();
System.out.println(myObj.x);
}
}
We can create multiple objects of one class:
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
Using Multiple Classes
We can also create an object of a class and
access it in another class. This is often used for better organization of
classes (one class has all the attributes and methods, while the other class
holds the main() method (code to be executed)).
Remember that the name of the java file should
match the class name. In this example, we have created two files in the same
directory/folder:
●
Main.java
●
Second.java
Main.java
public class Main {
int x = 5;
}
Second.java
class Second {
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
And the output will be:
5
Modify Attributes
We can also modify attribute values
public class Main {
int x;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 40;
System.out.println(myObj.x);
}
}
Example
Change the value of x to 25:
public class Main {
int x = 10;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 25; // x is now 25
System.out.println(myObj.x);
}
}
If We don't want the ability to override
existing values, declare the attribute as final:
Example
public class Main {
final int x = 10;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}
The final keyword is useful
when We want a variable to always store the same value, like PI (3.14159...).
Comments
Post a Comment