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

Classes and Objects in Java

1. A class in Java is a collection of fields and methods that operate on those fields. Fields are also called instance variables that hold data, while methods define behaviors. 2. To define a class, we use the class keyword followed by the class name. Inside the class body we can declare fields and methods. 3. Objects are instances of a class that are created using the new keyword. Objects allow us to access and manipulate the data and behaviors defined in a class.

Uploaded by

Arjun Choozhi
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Classes and Objects in Java

1. A class in Java is a collection of fields and methods that operate on those fields. Fields are also called instance variables that hold data, while methods define behaviors. 2. To define a class, we use the class keyword followed by the class name. Inside the class body we can declare fields and methods. 3. Objects are instances of a class that are created using the new keyword. Objects allow us to access and manipulate the data and behaviors defined in a class.

Uploaded by

Arjun Choozhi
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 41

Classes and Objects in Java

Basics of Classes in Java

1
Classes

 A class is a collection of fields (data) and


methods (procedure or function) that
operate on that data.

Circle

centre
radius

circumference()
area()

2
Classes
 A class is a collection of fields (data) and methods
(procedure or function) that operate on that data.
 The basic syntax for a class definition:
class ClassName [extends
SuperClassName]
{
[fields declaration]
[methods declaration]
}
 Bare bone class – no fields, no methods

public class Circle {


// my circle class
}
3
Syntax to declare a class:
class <class_name>{  
    data member;  
    method;  
}  
Adding Fields: Class Circle with fields

 Add fields
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle

 The fields (data) are also called the


instance varaibles.

5
Adding Methods

 A class with only data fields has no life. Objects


created by such a class cannot respond to any
messages.
 Methods are declared inside the body of the
class but immediately after the declaration of
data fields.
 The general form of a method declaration is:
type MethodName (parameter-list)
{
Method-body;
}

6
Adding Methods to Class Circle
public class Circle {

public double x, y; // centre of the circle


public double r; // radius of circle

//Methods to return circumference and area


public double circumference() {
return 2*3.14*r;
}
public double area() {
Method Body
return 3.14 * r * r;
}
}
7
Data Abstraction

 Declare the Circle class, have created a


new data type – Data Abstraction

 Can define variables (objects) of that


type:

Circle aCircle;
Circle bCircle;

8
Class of Circle cont.

 aCircle, bCircle simply refers to a Circle


object, not an object itself.

aCircle bCircle

null null

Points to nothing (Null Reference) Points to nothing (Null Reference)


9
Creating objects of a class

 Objects are created dynamically using the


new keyword.
 aCircle and bCircle refer to Circle objects
aCircle = new Circle() ; bCircle = new Circle() ;

10
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;

bCircle = aCircle;

11
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;

bCircle = aCircle;

Before Assignment Before Assignment


aCircle bCircle aCircle bCircle

P Q P Q

12
Automatic garbage collection

 The object Q
does not have a
reference and cannot be used in future.

 The object becomes a candidate for


automatic garbage collection.

 Java automatically collects garbage


periodically and releases the memory
used to be used in the future.
13
Accessing Object/Circle Data

 Similar to C syntax for accessing data


defined in a structure.
ObjectName.VariableName
ObjectName.MethodName(parameter-list)

Circle aCircle = new Circle();

aCircle.x = 2.0 // initialize center and radius


aCircle.y = 2.0
aCircle.r = 1.0

14
Executing Methods in Object/Circle

 Using Object Methods:


sent ‘message’ to aCircle

Circle aCircle = new Circle();

double area;
aCircle.r = 1.0;
area = aCircle.area();

15
class Student1{  
 int id;//data member (also instance variable)  
 String name;//data member(also instance variable)
  
  
 public static void main(String args[]){  
  Student1 s1=new Student1();//creating an object
 of Student  
  System.out.println(s1.id);  
  System.out.println(s1.name);  
 }  
}  
Output:0 null
class Student2
{  
 int rollno;  
 String name;  
  
 void insertRecord(int r, String n)
{  //method  
  rollno=r;  
  name=n;  
 }  
  
 void displayInformation(){System.out.println(rollno+" "+name);}//method  
  
 public static void main(String args[]){  
  Student2 s1=new Student2();  
  Student2 s2=new Student2();  
  
  s1.insertRecord(111,"Karan");  
  s2.insertRecord(222,"Aryan");  
  
  s1.displayInformation();  
  s2.displayInformation();  
  
 }  
}  
18
 A class can contain any of the following variable
types.
 Local variables: Variables defined inside methods,
constructors or blocks are called local variables.
 Instance variables: Instance variables are variables
within a class but outside any method.
 Class variables: Class variables are variables
declared with in a class, outside any method, with
the static keyword.

19
Method overloading in java
 If a class have multiple methods by same name but
different parameters, it is known as Method
Overloading. overloading is a compile time
phenomenon.
 Advantage of method overloading is it increases the
readability of the program.
 Different ways to overload the method
 There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type

 In java, Method Overloading is not possible by


changing the return type of the method.

20
Example of Method Overloading by changing the no. of arguments

class Calculation{  
  void sum(int a,int b)
{
System.out.println(a+b);
}  
  void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
  public static void main(String args[]){  
  Calculation obj=new Calculation();  
  obj.sum(10,10,10);  
  obj.sum(20,20);  
    }  
}  

21
Example of Method Overloading by changing data type of
class Calculation2{   argument
  void sum(int a,int b)
{
System.out.println(a+b);
}  
  void sum(double a,double b)
{
System.out.println(a+b);
}  
  
  public static void main(String args[])
{  
  Calculation2 obj=new Calculation2();  
  obj.sum(10.5,10.5);  
  obj.sum(20,20);  
  }  
}  

22
Method Overloaing is not possible by changing the return type of
method

class Calculation3{  
  int sum(int a,int b){System.out.println(a+b);}  
  double sum(int a,int b){System.out.println(a+b);}  
  
  public static void main(String args[]){  
  Calculation3 obj=new Calculation3();  
  int result=obj.sum(20,20); //Compile Time Error  
  
  }  
}  

23
Can we overload main() method?
Yes, by method overloading. You can have any number of main
methods in a class by method overloading.

class Overloading1
{  
  public static void main(int a)
{  
  System.out.println(a);  
  }  
    
  public static void main(String args[]){  
  System.out.println("main() method invoked");  
  main(10);  
  }  
}  

24
Method Overloading and TypePromotion

25
Example of Method Overloading with TypePromotion
class OverloadingCalculation1{  
  void sum(int a,long b)
{
System.out.println(a+b);
}  
  void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}  
  
  public static void main(String args[]){  
  OverloadingCalculation1 obj=new OverloadingCalculation1();  
  obj.sum(20,20);//now second int literal will be promoted to long  
  obj.sum(20,20,20);  
  
  }  
}  

26
If there are matching type arguments in the method, type promotion is not
performed

class OverloadingCalculation2{  
  void sum(int a,int b)
{System.out.println("int arg method invoked");}  
  void sum(long a,long b)
{System.out.println("long arg method invoked");}  
  
  public static void main(String args[]){  
  OverloadingCalculation2 obj=new OverloadingCalculation2();  
  obj.sum(20,20);//now int arg sum() method gets invoked  
  }  
}  

27
If there are no matching type arguments in the method, and each
method promotes similar number of arguments, there will be
ambiguity.

class OverloadingCalculation3{  
  void sum(int a,long b){System.out.println("a method invoked");}  
  void sum(long a,int b){System.out.println("b method invoked");}  
  
  public static void main(String args[]){  
  OverloadingCalculation3 obj=new OverloadingCalculation3();  
  obj.sum(20,20);//now ambiguity  
  }  
}  

28
Constructor in Java

 Constructor in java is a special type of


method 
 Syntax

 className()

{ ....... .......
}
that is used to initialize the object.
 Advantages of constructors in Java
 A constructor eliminates placing the
default values.
 A constructor eliminates calling the
normal or ordinary method implicitly.
31
class Sum
{ int a,b;
Sum()
{
a=10;
b=20;
}
public static void main(String s[])
{ Sum s=new Sum();
c=a+b;
System.out.println("Sum: "+c);
}
}
 Rules or properties of a constructor
 Constructor will be called automatically when the
object is created.
 Constructor name must be similar to name of the
class.
 Constructor should not return any value even void
also. Because basic aim is to place the value in the
object. (if we write the return type for the constructor
then that constructor will be treated as ordinary
method).
 Constructor definitions should not be static. Because
constructors will be called each and every time,
whenever an object is creating.
 Constructor should not be private provided an object
of one class is created in another class (Constructor
can be private provided an object of one class created
in the same class).
 Constructors will not be inherited from one class to
another class (Because every class constructor is create
for initializing its own data members).
 The access specifier of the constructor may or may not
be private.
 If the access specifier of the constructor is private then
an object of corresponding class can be created in the
context of the same class but not in the context of
some other classes.
 If the access specifier of the constructor is not private
then an object of corresponding class can be created
both in the same class context and in other class
context.

34
Method Constructor

1 Method can be any Constructor must be


user defined name class name
2 Method should have It should not have
return type any return type
(even void)
3 Method should be It will be called
called explicitly either automatically
with object reference whenever object is
or class reference created

4 Method is not The java compiler


provided by compiler provides a default
in any case. constructor if we do
not have any
constructor
A constructor that have no parameter is known as default
constructor.

JAVA Default Constructor


Syntax of default constructor:
<class_name>()
{
}  

 If there is no constructor in a class, compiler automatically creates


a default constructor.
class Test
{
int a, b;
Test ()
{ System.out.println("I am from default Constructor...");
a=10; b=20;
System.out.println("Value of a: "+a); System.out.println("Value of
b: "+b);
}
}; class TestDemo
{
public static void main(String [] args)
{
Test t1=new Test ();
}
};
parameterized constructor
If any constructor contain list of variable in its signature
is known as paremetrized constructor. A parameterized
constructor is one which takes some parameters.
Syntax
class ClassName
{ .......

ClassName(list of parameters)
{ .......
} .......
}
 class Test { int a, b; Test(int n1, int
n2) { System.out.println("I am from
Parameterized Constructor..."); a=n1;
b=n2; System.out.println("Value of a =
"+a); System.out.println("Value of b =
"+b); } }; class TestDemo1 { public
static void main(String k []) { Test
t1=new Test(10, 20); } };
 class Test { int a, b; Test () { System.out.println("I
am from default Constructor..."); a=1; b=2;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b); } Test (int x,
int y) { System.out.println("I am from double
Paraceterized Constructor"); a=x; b=y;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b); } Test (int x) {
System.out.println("I am from single Parameterized
Constructor"); a=x; b=x; System.out.println("Value of
a ="+a); System.out.println("Value of b ="+b); } Test
(Test T) { System.out.println("I am from Object
Parameterized Constructor..."); a=T.a; b=T.b;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b); } }; class
TestDemo2 { public static void main (String k [])
{ Test t1=new Test (); Test t2=new Test (10, 20);
Test t3=new Test (1000); Test t4=new Test
(t1); } };
 Why overriding is not possible at
constructor level.
 The scope of constructor is within the class so that
it is not possible to achieved overriding at
constructor level.
 Does constructor return any value?
 Ans:yes, that is current class instance (You
cannot use return type yet it returns a value).
 Can constructor perform other tasks instead of
initialization?
 Yes, like object creation, starting a thread, calling
method etc. You can perform any operation in the
constructor as you perform in the method.

You might also like