Java Chap 3 Part-I
Java Chap 3 Part-I
Java Chap 3 Part-I
Introduction
Defining a class
o Adding variables
o Adding methods
Creating objects
Accessing class members
Constructors
Method Overloading
Static members
Nesting of methods
Final methods
Introduction:
Java is an Object-Oriented Language. That means it uses Object as a primary resource of
programming. Objects are seen by the viewer or user, performing tasks assigned by you. Object-
oriented programming aims to implement real-world entities in programming. The main aim of OOP
is to bind together the data and the functions that operate on them so that no other part of the code
can access this data except that function.
Java supports the following fundamental concepts:
Polymorphism Objects
Inheritance Instance
Encapsulation Method
Abstraction Message Passing
Classes
Defining a Class: - A class can be defined as a template/blueprint that describes the behavior/state
that the object of its type supports. Class is also a user-defined data type. So once a the class type has
been defined, we can create “variables” of that type. In Java, these variables are termed as instances/
objects of classes. The basic form of class definition is:
Syntax:
class classname [extends superclassname]
{
Variable declaration
Method declaration
}
Adding Methods:
A class without methods has no meaning. The objects created by such a class cannot respond to
any messages.
We must have to add methods for manipulating the data contained in the class.
Methods are declared inside the body of the class.
A class can have any number of methods to access the value of various kinds of methods.
Syntax:
return_type methodname(parameter_list)
{
Method-body
}
Method declarations have four basic parts-
o The method name
o Return type
o Parameter List
o Body of the method
Example:
class Rectangle
{
int length, width;
Creating an Object
As mentioned previously, a class provides the blueprints for objects. So basically, an object is created
from a class. In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class:
Declaration: A variable declaration with a variable name with an object type.
Instantiation: The 'new' keyword is used to create the object.
Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the
new object.
Following is an example of creating an object:
class Rectangle
{
int length, width;
int Area()
{
int area = length * width;
return (area);
}
int Area()
{
int area = length * width;
return (area);
}
r1.getData(5,7);
int ans = r1.Area();
System.out.println(“Area = ” + ans);
}
}