0% found this document useful (0 votes)
26 views

2.classes and Objects-1

The document discusses classes and objects in Java, explaining that classes define the structure and behavior of objects through methods and variables, while objects are instances of classes that allocate memory at runtime and can access class methods and variables. It also covers key concepts like constructors, which initialize objects, and different types of methods including instance methods, class methods, and returning values.

Uploaded by

amoldivate0077
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

2.classes and Objects-1

The document discusses classes and objects in Java, explaining that classes define the structure and behavior of objects through methods and variables, while objects are instances of classes that allocate memory at runtime and can access class methods and variables. It also covers key concepts like constructors, which initialize objects, and different types of methods including instance methods, class methods, and returning values.

Uploaded by

amoldivate0077
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

CLASSES AND OBJECTS

BY: Prof. Pavan Malani


Class :
 Class encapsulates a group of logically related data items and functions
together that works on them .
 The variables which are declared inside the class by default Public or
friendly it means they are accessible throughout the program.
Object :
 Once the class is defined then only we can create object of that class.
 Once the object are created then we can access methods or variables
of the Class.
class_name Object_name = new class_name();
Eg. abc t= new abc();
Here t is the instance or object of class abc
Garbage Collection :
When an object of a class is no longer referred by any variable of
a class then java automatically releases(free) the memory occupied
by that object is known as garbage collection.
It is same as destructor in C++.
Variables in Java :There are 2 types of variables in Java.
i) Instance variable
ii) Class variable
i)Instance Variable:
They are declared in the same way as that of a local variable but
this variable can access only inside the class.
ii) Class variable:
They are global to a class and only instance of the class are access
this type of variable. To declare a class variable keyword static is
used.
The default value of class variable is zero
 Methods(functions) in Java :
I) Instance Method: They are just like a normal function instance method can
access both instance variable as well as class variable.
-Syntax :
return type method name(argument)
{
body
}
ii)Class method:
Class methods are like a class variable .
There are 2 conditions of class method:
1)This method can access only other class variable, they are not operate on
instance variable .
2)To call the class method class name is required instead of object name.
Syntax : static return type method name(argument )
{
body

}
class demo static void disp()
{ {
int a,b; System.out.println(“the value of c” +c);
static int c; }
void get()
public static void main(String args[])
{
{
a=10;
demo t= new demo();
b=20;
c++; t.get();
} t.show();
void show() demo.disp();
{ }
System.out.println(“the value of a & b” +a+“”+b); }
}
Using Two Different Classes
class demo static void disp()
{ {

int a,b; System.out.println ("The value of c" +c);


}
static int c;
}
void get();
class test1
{
{
a=10;
public static void main (String args[])
b = 20;
{
c++;
demo t= new demo ();
} t.get();
void show() t.show() ;
{ demo.disp();
System.out. println ("The value of a & b “+a+“ +b ); }
} }
save the above code by test1.java because
main method is return in that class
Method with parameter passing
class box class test2
{ {
int ļ, w, h; public static void main( String args[])
void getinfo(int len, int wid,int hgt) {
{ box t= new box ();
l=len; t.getinfo (10,20,30);
w=wid; t. show();
h=hgt; }
} }
void show()
{
System.out.println ("The box dimension “+l+ "x"+w+ "x" +h);
}
}
Function with Returning value
A function can be return a value to a calling program
whenever necessary.
At a time only one value is return from function or we
can return array or object.
While returning value from function we must specify
specific return type otherwise return type is void.
class box
class test2
{
{
int l,w, h;
public static void main( String args [])
void getinfo(int len, int wid,int hgt)
{
{
box t= new box();
l=len;
t.getinfo(10,20,30);
w= wid;
t.show();
h = hgt;
int z=t.getVolume();
}
System.out.println(“ The value of box z"
void show() +z);
{ }
System.out.println(" The box dimension "+l+"x" +w+”x “ +h); }
}
int getvolume()
{
return(l*w*h);
}
}
Write a program to find factorial of number pass number as a
parameter to function return output to the calling program
class factorial
{ class test 3

int fact; {

void getinfo (int f) public static void main(String args[])

{ {

fact=f; factorial t1=new factorial();

} t1. getinfo(5);

int cal() int ans= t1.cal();

{ int i=1,n=1; System.out.println (" The value of f ” +ans);

while (i<=fact) }

{ n=n*i; }

i++;
} return(n);
}
Constructor :
A constructors are the special members of the class which have same
name as that of class name.
They are used to do initialization of the object at the time of creation
so it is called as automatic initialization of the object.
Initializing the object means to assign some initial value to data
members of the object.
Properties of constructor
1. The constructor function of a class have same name as the class
name.
2. The constructor does not have any return type therefor it does not
return any value.
Types of constructor
1 ) Default constructor: The constructor that does not accept any
argument is known as default constructor.
2) Parameterized constructor :It is the constructor with one or more
argument passed in it.
3) Overloading constructor : If a class can have multiple constructor
with different types of argument such a constructor is called
overloading of constructor.
4) Copy Constructor :If parameters to the constructor can be object
reference of the same class such constructor is called copy
constructor.
Demo Program w= t.w;
class box h=t.h;
{ }
int l,w,h ; void show ()
box() //default constructor {
{ System.out.println("The dimension "+l+" x”+w +"x" +h);
l=w=h=-1; }
} }
box (int d) //Parameterized Constructor class test3
{ {
l=w=h=d; public static void main ( String args[])
} {
box ( int len,int wid, int hgt) box b1 = new box();
{ box b2 = new box(5);
l= len; box b3 = new box (10,20,30);
w=wid; box b4 = new box (b3);
h=hgt; b1.show();
} b2.show();
box (box t) // Copy Constructor b3.show();
{ b4.show();
I=t.l; }
}
Write a program which performs addition and subtraction of 2 complex no. initialize
the value through parameterised constructor
}
class complex
void show ()
{
{
double r,i;
system.out.println (r+“+i”+i);
complex()
}}
{ }
class tes14
complex (double real, double img) {
{ public static void main (String args[])
r=real; {
i = img; complex t=new complex (4.5f, 2.2f);
} complex t1=new complex( 2.2f,1.3f);

void addcomp(complex a,complex b) t.show();


t1.show();
{
complex t3=new complex();
r=a.r+b.r;
t3.addcomp(t,t1);
i=a.i+b.i;
t3.show();
}
t3.subcomp(t,t1);
void subcomp( complex a, complex b)
t3.show();
{ r=a.r-b.r; }
i= a.i-b.i; }
Finalized Method :
Java has an automatic garbage collection mechanism to clean up the memory which is not in
used, but garbage collection does not release the all the resources such as file handler,
windows character font, graphics object etc. then we have to ensure that these resources are
freed before object is destroyed. To handle such situations java uses finalization.
by defining finalize() method in the class. The purpose of finalize method is to free
the resources which are not free by garbage collection.
Syntax: protected void finalize()
{
//code
}
Overloading of methods
Methods each with a same name but different argument list known as overloading of
methods. Java allows method overloading as long as parameter list is unique for the same
method name compiler differentiates the overloaded method with the same name based on
number and type of argument but not on return type & name.
Eg 1. class test21
class overload {
{ public static void main(String args [])
void add(int a,int b) {
{ overload b = new overload();
System.out.println("Addition" of 2 int " + (a+b)); b.add (4,5);
} b. add (3.2f, 8);
void add( float a, float b) b. add (3.2f, 5.2f);
{ }
System.out.println(" Addition 2 float is " +(a+b)); }
}
void add ( float a,int b)
{
System.out.println(" Addition" is "+(a+b));
}
}
2.WAP to find out area of circle, Square, rectangle by using
method overloading
void area(int s)
class overload {
{ int sq = S*S;
void area( float r) System.out.println(" Area of square is” +sq);
{ }
float c= 3.14f * r *r; }
System.out.println(" Area of circle is "+c); class test2
} {
void area(int l, int b) public static void main(String args[])
{ {
int r=l*b; Overload t= new Overload ();
System.out.println(" Area of rectangle is " + r); t1.area(5);
} t.area (4,5);
t. area ( 3.2f);
}
}
Predefined Classes :
The Java API provides a rich set of classes and interfaces organized in
package
There are 2 important classes :
1) Object Class
2) Wrapper Class
1)Object Class: The most important predefined class is the object class.
It is at the top of class hierarchy in Java . It is the most important
because all the classes in Java derived from this class. The object class
defines the basic state and behavior that all object must have such as
ability to compare with another object, to convert string to object etc.
Method of object class :
1) equals () :
Syntax : Boolean equals (object)
This method is use to compare two objects for their equality. It returns true if the
objects are equal otherwise returns false.
String S1 = new String ("Hello") ;
String S2 = new String ("Hello");
if (s1.equals (S2))
System.out.println (“Objects are equal");
else
System.out.println (" Objects are not equal ");
2) clone() :
Syntax : protected object clone()
Creates & returns copy of original object so if we made any changes in original object
it will not reflect on its clone.
3) toString():It returns string representation of object.
2) Wrapper class :
Java offers to convert primitive data types into object by using wrapper class. If Java
compiler can make automatic conversion between primitive datatypes and respective object
is known as autoboxing.
When java converts wrapper class into primitive datatype known as unboxing.

Primitive Data type Wrapper class


1) int Integer

2) float Float
3) char Character

4) double Double

5) boolean Boolean

6) long Long
final Keyword :
There are 3 purpose of final Keyword
First to declare constant.
I) We can declare a variable in any scope to be final, The value of final variable cannot be
changed throughout the program once it has been initialize.
eg. final int i=10
Here the value of ì remains constant throughout the program.
Note: If we declare final variable & initialized that variable later this is known as blank final.
e.g. final int i;
-------------
------------- blank final
-------------
i=10;
2) Prevent Inheritance(final class):
To prevent the class being further sub class from the base class we use final keyword before
the class declaration i.e we prevent inheritance.
3) To prevent method Overriding (final method) :
Overriding means base class & derived class contains the same method name with Same
parameters then the method of derived class hides the method of base class. To prevent
such a method overriding we use final key word before method declaration.

Command line argument :


Java allows to accept the input from command line. Benefit of command line argument
is that we can pass any type of input at the time of execution of program. This arguments
are stored in the parameter args which are passed in main method.
In Java datatype of argument which is accepted through console or command line is of
string type so we have to convert string type into int , float etc for this purpose we use
method parseInt() parseFloat ()
eg String i = "2";
String t="2.5F" ;
int z = Integer.parseInt (i);
float p = Float.parseFloat(t);
1)Write A Program to accept argument through command line
& display this argument.
class command
{
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
{
System.out.println(args [i]);
}
}
}
Output:
Javac command.java
Java command 10 20
args [0] args[1]
Write a program to accept two no from command line perform their
addition and substraction
class operation class test_22
{ {
int a,b; public static void main (String args[])
void accept(int p, int q) {
{ int x = Integer.parseInt(args[0]);
a=p; int y = Integer.parseInt(args [1]);
b=q; operation t = new operation ();
} t.accept (x,y);
void cal() t.cal();
{ }
int ans=a+b; }
int ans1=a-b;
System.out.println("Addition is” +ans);
System.out.println("subtraction is” +ans1);
}
}
Write a program to accept 1 no from command line and
performs Addition from 1 to that no.
class sum
{
public static void main ( String args[])
{
int n = Integer.parseInt (args [0]);
int i, sum = 0;
for (i=0; i<n; i++)
{
sum = sum + i;
}
System.out.println ("Addition of nos is " + süm);
}
}
WAP to accept no from command line & find the factor of that no display even
factor and odd factor separately
class factor {
{ System.out.println ("even factor” +i);
int n; else
void getdata(int no) System.out.println (“odd factor” +i);
{ }
n=no; }
} }}
void cal() class test23
{ {
int i=1; public static void main(String args[])
while(i<=n) {
{ factor t1 = new factor();
if (n%i ==0) int p=Integer.parseInt(args [0]);
{ t.getdata (p);
if(i%2==0) t.cal();
}
}
WAP to accept roll no, marks, name of three subject from command line .
Calculate total and percentage and display it. Use parameterised method
class Student Void show()

{ {

int rno, m1, m2, m3; Sop (rno "+ "+name);

String nm; }

void get(int r, String name , int m1,int m2, int m3) }

{ class test36

rno=r; {

nm = name; psvm(string args ([])

m1=m11; {

m2 = m21; int r = Integer.parseInt (args[0]);

m3 = m31; String n=args[1];

} int m1=Integer.parseInt(args[2]);

void cal() int m2 = Integer.parseInt( args[3]);

{ int m3 = Integer.parseInt(args[4]);

int tot = m1+m2+m3; student t= new student();

float per =(float)*tot/3; t.get (r,n,m1,m2,m3);

Sop (" Total marks " + tot); t.show();

Sop(" Percentage is "+ per); t.cal();

} }

} }

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy