Each class is a collection of data and the functions that manipulate the data. The data components of the class are called data fields and the function components of the class are called member functions or methods.
Defining Classes in Java
Each
class is a collection of data and the functions that manipulate the data. The
data components of the class are called data fields and the function components
of the class are called member functions or methods.
• Thus
the state of an object is represented using data fields (data members) and
behaviour of an object is represented by set of methods (member functions). The
class template can be represented by following Fig. 1.14.1.
• The
Java Class can written as follows
class
Customer {
int ID;
int Age;
String
Name;
Customer()
{
}
Customer(int
ID) {
}
double
withdraw_money() {
…..
…..
}
• Encapsulation
means binding of data and method together in a single entity called class. Thus
a class is used to achieve an encapsulation property.
• This
class is not having the main function. The class that contains main function is
called main class.
• Following
is a simple Java program that illustrates the use of class
//Program for demonstrating the concept of
class
import
java.io.*;
import
java.lang.*;
import
java.math.*;
public
class MyClass
{
String
name;
int
roll;
double
marks;
public
void display(String n,int r,double m)
{
System.out.println();
System.out.println("Name:
"+n);
System.out.println("Roll
number: "+r);
System.out.println("Marks:
"+m);
}
public
static void main(String args[])
{
int a,b;
MyClass
obj1= new MyClass();
MyClass
obj2=new MyClass();
MyClass
obj3=new MyClass();
obj1.display("Amar",
10,76.65);
obj2.display("Akbar",
20,87.33);
obj3.display("Anthony",30,96.07);
}
}
Output
Name:
Amar
Roll
number: 10
Marks:
76.65
Name:
Akbar
Roll
number: 20
Marks:
87.33
Name:
Anthony
Roll
number: 30
Marks:
96.07
Program Explanation
• In
above program we have declared one simple class. This class displays small
database of the students. The data members of this class are name,roll and
marks. There is one member function named display which is for displaying the
data members. In the main function we have created three objects obj1,obj2 and
obj3. These objects represent the real world entities. These entities are
actually the instances of the class. The class representation of the above
program can be as follows-
Object Oriented Programming: Unit I: Introduction to OOP and Java : Tag: : with Example Java Program - Defining Classes in Java
Object Oriented Programming
CS3391 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation