Java Unit 3 (3.2 3.3)
Java Unit 3 (3.2 3.3)
Java Class
class class_name
{
field;
method;
}
class Student
{
int rollno;//instance variable
String name;
void display(){ }//method
}
A simple class example
Suppose, Student is a class and student's name, roll number, age are
its fields and info() is a method. Then class will look like below.
class Student
{
String name;
int rollno;
int age;
void info()
{
// some code
}
}
This is how a class look structurally. It is a blueprint for an
object. We can call its fields and methods by using the object.
The fields declared inside the class are known as instance
variables. It gets memory when an object is created at
runtime.
Methods in the class are similar to the functions that are
used to perform operations and represent behavior of an
object.
Java Object
s2
Program
public class Student
{
String name;
int rollno;
int age;
void info()
{
System.out.println("Name: "+name);
System.out.println("Roll Number: "+rollno);
System.out.println("Age: "+age);
}
public static void main(String[] args)
{
Student student = new Student();
// Accessing and property value
student.name = "Ramesh";
student.rollno = 253;
student.age = 25;
// Calling method
student.info();
}
}
In case, if we don’t initialized values of class fields then
they are initialized with their default values.
public class Student
{
String name;
int rollno;
int age;
void info()
{
System.out.println("Name: "+name);
System.out.println("Roll Number: "+rollno);
System.out.println("Age: "+age);
}
public static void main(String[] args)
{
Student student = new Student();
// Calling method
student.info();
}
}
O/P
Name: null
Roll Number: 0
Age: 0
Default values of instance variables
111 Karan 0
222 Aryan 25