Classes, Objects and Methods
Class
Structures are very similar to Classes in that they collect data
together. A class is collection of objects of similar type.
However, classes extend this idea and are made from two
different things:
► Attributes - things that the object stores data in, generally
variables.
► Methods - Functions and Procedures attached to an Object
and allowing the object to perform actions
Object
► An object is a component of a program that knows how to
perform certain actions and how to interact with other elements
of the program.
► Objects are the basic units of object-oriented programming.
Defining a Class
Syntax :
class classname
{
field declarations;
method declaration;
}
Ex: class Rectangle
{
}
Fields Declaration
Syntax:
class classname
{
type variable_name;
}
Ex: class Rectangle
{
int length;
}
Methods declaration
Syntax:
type methodname(parameter-list)
{
method body;
}
Ex: void area(int a, int b)
{
method body;
}
Example of class
class Rectangle
{
int length;
int width;
void getData(int x,int y)
{
length=x;
width=y;
}
}
Creating Objects
► Objects in java are created using the new operator.
► The new operator creates an object of the specified class
and returns a reference to that object.
Ex:
Rectangle rect; //declare the object
rect=new Rectangle(); //instantiate the object
or
Rectangle rect=new Rectangle();
Accessing class members
Syntax:
[Link]=value;
[Link](parameter_list);
Ex:
[Link]=15;
[Link](15,10);
Example 1 class RectArea
{
int length,width;
void getData(int x,int y)
{ length=x;
width=y;
}
int Area()
{
int area=length*width;
return(area);
}
public static void main(String args[])
{
int a;
RectArea rect=new RectArea();
[Link](20,12);
a=[Link]();
[Link]("Area="+a);
}
}
Example 2 class Rectangle
{
int length,width;
void getData(int x,int y)
{
length=x;
width=y;
}
int rectArea()
{
int area=length*width;
return(area);
}
Contd…
class RectArea
{
public static void main(String args[])
{
int a;
Rectangle rect=new Rectangle();
[Link](20,12);
a=[Link]();
[Link]("Area="+a);
}
}
Example 4 class Rectangle
{
int length,width;
void getData(int x,int y)
{
length=x;
width=y;
}
int rectArea()
{
int area=length*width;
return(area);
}
class RectArea
Contd… {
public static void main(String args[])
{
int area1,area2;
Rectangle rect1=new Rectangle();
Rectangle rect2=new Rectangle();
[Link]=15;
[Link]=10;
area1=[Link]*[Link];
[Link](20,12);
area2=[Link]();
[Link]("Area1="+area1);
[Link]("Area2="+area2);
}
}
Question
WAP to find area of circle using classes,
objects and methods.
class Circle
Solution {
double Area(int x)
{
double area=3.14*x*x;
return(area);
}
}
class CircleArea
{
public static void main(String args[])
{
double area;
Circle cir=new Circle();
area=[Link](20);
[Link]("Area="+area);
}
}
Scope of Variables
Classification of variables
Local variables
► Local variables are declared in methods, constructors, or
blocks.
► Local variables are created when the method is entered
and the variable will be destroyed once it exits the
method.
► Access modifiers cannot be used for local variables.
► Local variables are visible only within the declared
method block.
► There is no default value for local variables so local
variables should be declared and an initial value should
be assigned before the first use.
Instance variable
► Instance variables are declared in a class, but outside a
method.
► Instance variables hold values that must be referenced by
more than one method.
► The instance variables are visible for all methods,
constructors in the class.
► Instance variables can be accessed directly by calling the
variable name inside the class. However within static
methods and different class ( when instance variables are
given accessibility) should be called using the fully
qualified name i.e. [Link].
Class variables
► Class variables also known as static variables are declared
with the static keyword in a class, but outside a method,
constructor or a block.
► There would only be one copy of each class variable per
class, regardless of how many objects are created from it.
► Visibility is similar to instance variables. However, most
static variables are declared public since they must be
available for users of the class.
Static Members
► The members that are declared static are called static
members.
► These members are associated with the class itself rather
than individual objects, the static variables and static
methods are often referred to as class variables and class
methods.
► Static variables are used when we want a variable common
to all instance of class.
► Static variables and methods can be called without using
objects. Instead they are called using class name.
e.g. static int count;
static int max(int x, int y)
Example of class Counter
static variable {
static int count=0;
void count()
{
count=count+1;
[Link](count);
}
public static void main(String args[])
{
Counter c1=new Counter();
[Link]();
Counter c2=new Counter();
[Link]();
Counter c3=new Counter();
[Link]();
}
}
Example of static method
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
public static void main(String args[])
{
int result=cube(5);
[Link](result);
}
}
Method Overloading
If a class have multiple methods by same name but
different parameters, it is known as Method
Overloading.
Different ways to overload the method :
1. By changing number of arguments
2. By changing the data type
3. Sequence of Data type of parameters.
Example of Method Overloading by changing the no. of arguments
class DisplayOverloading
{
void display(char c)
{
[Link](c);
}
void display(char c, int num)
{
[Link](c + " "+num);
}
} Contd…
Contd…
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
[Link]('a');
[Link]('a',10);
}
}
Question
WAP to add different type of numbers using
method overloading. Write different
functions to add int, float etc.
class AddOverload
Solution {
void add(int x, int y)
{
int z=x+y;
[Link]("x+y="+z);
}
void add(float x, float y)
{
float z=x+y;
[Link]("x+y="+z);
}
} contd…
Contd… class Addition
{
public static void main(String args[])
{
AddOverload ad=new
AddOverload();
[Link](20,10);
[Link](20.5f,10.5f);
}
}
Different ways to overload the method :
1. By changing number of arguments
2. By changing the data type
3. Sequence of Data type of parameters.
import [Link];
class add
{
void cal(int a, int b)
{
int z=a+b;
[Link](z);
}
double cal(int a, int b)
{
double z=a+b;
return (z);
}
public static void main(String args[])
{
add a1=new add();
Scanner sc=new Scanner([Link]);
int a=[Link]();
int b=[Link]();
[Link](a,b);
double aa=[Link](a,b);
[Link](aa);
}
}
import [Link];
class add
{
void cal(int a, int b)
{
int z=a+b;
[Link](z);
}
void cal(double a, double b)
{
double z=a+b;
[Link](z);
}
public static void main(String args[])
{
add a1=new add();
Scanner sc=new Scanner([Link]);
int a=[Link]();
int b=[Link]();
[Link](a,b);
[Link](a,b);
}
}
Constructor
► Constructor is a special type of method that is used to
initialize the object.
► Java constructor is invoked at the time of object
creation.
► It constructs the values i.e. provides data for the object
that is why it is known as constructor.
► The java compiler provides a default constructor if you
don't have any constructor.
Rules for creating java constructor
❑ Constructor name must be same as its class name
❑ Constructor must have no explicit return type
Types of constructors
Java Default Constructor
► A constructor that have no parameter is known as
default constructor.
► Syntax of default constructor:
<class_name>()
{
}
Example
class Bike1
{
Bike1() //default constructor
{
[Link]("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
parameterized constructor
► A constructor that have parameters is known as
parameterized constructor.
► Parameterized constructor is used to provide
different values to the distinct objects.
Example class Student
{
int id;
String name;
Student(int i,String n)
{
id = i;
name = n;
}
void display()
{ [Link](id+" "+name);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
[Link]();
[Link]();
}
}
Question
WAP to read and display the details of book with
the following specifications:
Data Members: book_name, book_author,
book_price
Use Parameterized constructors to initialize data
members of Book
Solution
class Book
{
String name;
String Author;
int price;
Book(String n,String a,int p)
{
name=n;
Author=a;
price=p;
} contd…
Contd… void display()
{
[Link]("name:"+name);
[Link]("Author:"+Author);
[Link]("Price:"+price);
}
public static void main(String args[])
{
Book b = new Book("Java:The Complete Reference","H.S.",300);
[Link]();
}
}
Constructor overloading
► Constructor overloading is a
technique in Java in which a class
can have any number of constructors
that differ in parameter lists.
► The compiler differentiates these
constructors by taking into account
the number of parameters in the list
and their type.
class Student
Example
{
int id;
String name;
int age;
Student(int i,String n)
{
id = i;
name = n;
}
Student(int i,String n,int a)
{
id = i;
name = n;
age=a;
} contd…
void display()
Contd… {
[Link](id+" "+name+" "+age);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
[Link]();
[Link]();
}
}
Question
WAP to calculate area of circle and triangle
using constructor overloading.
Solution import [Link];
class ConstructOverloadArea
{
ConstructOverloadArea(int r)
{
float area=3.14f*r*r;
[Link]("Area of circle: "+area);
}
ConstructOverloadArea(int h,int b)
{
float area=0.5f*h*b;
[Link]("Area of triangle: "+area);
} contd…
public static void main(String args[])
c {
o int radius,height,base;
n Scanner sc=new Scanner([Link]);
[Link]("enter redius of circle, height and base of triangle");
t
radius=[Link]();
d
height=[Link]();
… base=[Link]();
ConstructOverloadArea s1 = new ConstructOverloadArea(radius);
ConstructOverloadArea s2 = new ConstructOverloadArea(height,base);
}
}
Passing and Returning Objects in Java
► Although Java is strictly pass by value, the precise effect differs between
whether a primitive type or a reference type is passed.
► When we pass a primitive type to a method, it is passed by value. But when
we pass an object to a method, the situation changes dramatically, because
objects are passed by what is effectively call-by-reference. Java does this
interesting thing that’s sort of a hybrid between pass-by-value and pass-by-
reference.
► While creating a variable of a class type, we only create a reference to an
object. Thus, when we pass this reference to a method, the parameter that
receives it will refer to the same object as that referred to by the argument.
► This effectively means that objects act as if they are passed to methods by use
of call-by-reference.
► Changes to the object inside the method do reflect in the object used as an
argument.
class Calculate
{
int a;
int b;
Calculate (int x, int y)
{ a = x;
b = y;
}
void add(Calculate c1)
{
c1.a=c1.a +10;
c1.b=c1.b +10;
}
}
class CalculateDemo
{
public static void main(String args[])
{
Calculate c1 = new Calculate(10, 20);
[Link]("Before call:"+ c1.a +" "+c1.b);
[Link](c1);
[Link]("After call:"+ c1.a +" "+c1.b);
}
}
Example
WAP to find area of rectangle by passing object as
an arguments.
Solution class Rectangle
{
int length;
int width;
Rectangle(int l, int b)
{ length = l;
width = b;
}
void area(Rectangle r1)
{
int areaOfRectangle = [Link] * [Link];
[Link]("Area of Rectangle : " + areaOfRectangle);
}
} contd…
contd…
class RectangleDemo
{
public static void main(String args[])
{
Rectangle r1 = new Rectangle(10, 20);
[Link](r1);
}
}
Packages : Putting
classes together
Introduction
► A Package can be defined as a grouping of related types (classes,
interfaces, enumerations etc. ) providing access protection.
► Packages are used in Java in order to prevent naming conflicts, to control
access, to make searching/locating and usage of classes, interfaces,
enumerations easier.
► Package in java can be categorized in two form:
❑ built-in package/API packages (Application Programming Interface)
❑ user-defined package.
Java API Packages
Using system Packages
► Syntax :
import [Link];
or
import packagename.*;
Example :
import [Link];
import [Link].*;
Creating User Defined Packages
Creating our own packages involves the following steps:
1. Declare the package at the beginning of the a file using
the form.
2. Define the class that is to be put in the package and
declare it public.
3. Create a subdirectory under the directory where the main
source files are stored.
4. Store the listing as the [Link] file in the
subdirectory created.
5. Compile the file. This creates .class file in the
subdirectory.
Example
package firstpackage;
public class firstclass
{
…………
body of class
…………..
}
Accessing a Package
Syntax:
import package1[.package2][.package3].classname;
Example
import [Link];
import packagename.*;
Adding a class to a package
► Define a class and make it public.
► Place the package statement before the class.
package packagename;
► Store this as [Link] file under directory packagename.
► Compile the file. This will create .class file
Note: we can also add a non public class to a package using the
same procedure.
Creating Package
package p1;
public class A
{
public void displayA()
{
[Link](“Class A");
}
}
Creating Package
Importing a class
import p1.*;
class B
{
public static void main(String args[])
{
A objA=new A();
[Link]();
}
}
Importing a class
Importing classes from
other packages
Subclassing an
imported class
Importing class into
another package class
Static import
► The static import statement can be used to import static members from
classes and use them without qualifying the class name.
► Syntax:
import static [Link];
or
import static [Link].*;
Example without using static import
class Mathop
{
public static void main(String args[])
{
int r=2;
double area=[Link]*r*r;
[Link]("Area="+area);
}
}
Example using static import
import static [Link].*;
class Mathop
{
public static void main(String args[])
{
int r=2;
double area=PI*r*r;
[Link]("Area="+area);
}
}