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

Class&constructor

Uploaded by

ragulr239
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Class&constructor

Uploaded by

ragulr239
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Class Fundamentals

In Java, everything is encapsulated under classes. Class can be defined as a


template/blueprint that describes the behaviors/states of a particular entity. A class defines
new data type. Once defined, this new type can be used to create object of that type. Object is
an instance of class. You may also call it as physical existence of a logical template class.
A class is declared using class keyword. A class contains both data and code that operate on
that data. The data or variables defined within a class are called instance variables and the
code that operated on this data is known as methods.
The General Form of a Class
class classname [ extends baseclass implements interface1, interface2 ]
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;

type methodname1(parameter-list)
{
// body of method
}

type methodname2(parameter-list)
{
// body of method
}

// ...
type methodnameN(parameter-list)
{
// body of method
}
}
Rules for Java Class
• A Class can have only public or default(no modifier) access specifier.
• It can be either abstract, final or concrete(normal class).
• It must have the class keyword, and class must be followed by a legal identifier.
• It may optionally extend one parent class. By default, it will extend java.lang.Object
• It may optionally implement any number of comma-separated interfaces.
• The class’s variables and methods are declared within a set of curly braces {}
• Each .java source file may contain only one public class.
• Finally the source file name must match the public class name and it must have a .java
suffix.
Object
Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.
There are three steps when creating an object from a class:
 Declaration: A variable declaration with a variable name and object type.
 Instantiation: The 'new' key word is used to create the object.
 Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
The general syntax for declaring object
classname ref_var;
ref_var = new classname ( );
Here, ref_var is a variable of the class type being created. The classname is the name of the
class that is being instantiated. After the first line executes, ref_var contains the value null,
which indicates that it does not yet point to an actual object. The next line allocates an actual
object and assigns a reference to it to ref_var.
The new operator dynamically allocates memory for an object. The class name followed by
parentheses specifies the constructer for the class. A constructer defines what occurs when an
object of a class is created.
Assigning object reference variables
When you assign one object reference variable to another object reference variable, you are
not creating a copy of the object; you are only making a copy of the reference.

Methods
• A method is a collection of statements that are grouped together to perform an
operation.
• A method is a block of code which only runs when it is called.
The general form of a method is
type methodname (parameter-list) {
// body of method
}
Every method should specify the type of data to be returned. This can be any valid type,
including class types that you create. If the method does not return a value, its return type
must be void. The name of the method can be any valid identifier. The parameter-list is a
sequence of type and identifier pairs separated by commas. Parameters are variables that
receive the value of the arguments passed to the method when it is called.

Methods that have a return type other than void return a value to the calling routine using the
following form of the return statement:
return value;
Accessing Instance Variables and Methods:
Instance variables and methods are accessed via created objects. To access an instance
variable the fully qualified path should be as follows:
/* First create an object */
ObjectReference = new Constructor ();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName()
Example1
class Pencil
{
private String color = "red";

public void setColor (String newColor) {


color = newColor;
}
public String getColor(){
return color;
}
public static void main(String[] args)
{
Pencil p = new Pencil(); //Object creation
p.setColor("red");
System.out.println("Pencil color is "+p.getColor()):
}
}
Example2
package javalab;
import java.util.*;
public class Circle
{
double radius;
void setRadius(double r)
{
radius=r;
}
double displayArea()
{
return Math.PI*radius*radius;
}
double displayPeri()
{
return 2*Math.PI*radius;
}
public static void main(String [] args)
{
Scanner in=new Scanner(System.in);
double r;
System.out.println("Enter Radius: ");
r=in.nextDouble();
Circle obj=new Circle ();
obj.setRadius(r);
System.out.println("Area of Circle: "+obj.displayArea());
System.out.println("Perimeter of Circle:"+obj.displayPeri());
}
}
Constructors
• A constructor is a special method that is used to initialize an object upon creation.
• Constructors have the same name as class name in which it resides.
• They have zero or more parameters.
Characteristics of Constructors
• Constructors cannot be private.
• Constructor in java cannot be abstract, static, final or synchronized. These modifiers
are not allowed for constructors.
• Constructors cannot be inherited.
• Constructors are automatically called when an object is created.
• A constructor does not have any return type, not even void.
• Constructors can be overloaded. (i.e) A class can have more than one constructors
• Every class has a constructor. If you don’t explicitly declare a constructor for a java
class, the compiler builds a default constructor for that class.
Types of Constructors
• Default constructor - Constructor with no argument is called default constructor.
Example1
class Point
{
int x, y;
Point( ){ //Default Constructor
x = y = 0;
}

}
Example2
class NoteBook
{
/*This is default constructor. A constructor does
not have a return type and it's name
should exactly match with class name */
NoteBook(){
System.out.println("Default constructor");
}
public void mymethod()
{
System.out.println("Void method of the class");
}
public static void main(String args[]){
/* new keyword creates the object of the class
and invokes constructor to initialize object*/
NoteBook obj = new NoteBook();
obj.mymethod();
}
}
Output
Default constructor
Void method of the class

• Parameterized Constructors - Constructor with parameter is called parameterized


constructor.
Example
class Point
{
int x, y;
Point(int i,int j){ //Parameterized Constructor
x = i;
y = j;
}

}
Example2
class Student{
int id;
String name;
//creating a parameterized constructor
Student(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student s1 = new Student(101,"Kavya");
Student s2 = new Student(102,"Surya");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output
101 Kavya
102 Surya

Overloading Constructors
Like methods, a constructor can also be overloaded. Overloaded constructors are
differentiated on the basis of their type of parameters or number of parameters. Constructor
overloading is not much different than method overloading.
Example
class Point
{
private int x,y;
Point() //default constructor
{
x = y = 0;
}
Point(int i, int j) //parameterized constructor with 2 argument
{
x = i;
y = j;
}
public void display()
{
System.out.println(x+" , "+y);
}
public static void main(String[] args)
{
Point p1 = new Point();
Point p2 = new Point(10,20);
p1.display();
p2.display();
}
}
Output
0,0
10 , 20

You might also like