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

Unit-2 - Classes, Object & Methods

Core java

Uploaded by

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

Unit-2 - Classes, Object & Methods

Core java

Uploaded by

Aryan Gireesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

CH-2

OBJECTS, CLASSES
AND METHODS
Class
Class can be defined as a template or blueprint that
describe the behaviors 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.
Syntax:
class classname
{
type instance-variable1;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}
Objects Of Same Kinds
❖These are instances of class SmartPhone.

❖Class stands for blueprint from which individual objects are


created.

❖Each phone has some componenets which categorizes it into a


SmartPhone
Class SmartPhone
{
String manufacturer;
String model;
double storage;
double screensize;
}
Class
❖Defines new data type(primitive ones are not enough). Eg.
SmartPhone

❖This new type is used to create object of that type.

❖So, Class is a template for an object and an object is instance of


class.
Example:
class Box
{
double width;
double height;
double depth;
}

Only template has created. We can have thousand of different boxes


like magic box,soap box etc.
Now,Let’s create new object!

Box soapbox =new Box();

Height
Soapbox Length
Width

Each Object has its own set of instance variable.


//Program to calculate volume of box.
class Box
{
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class boxdemo
{
public static void main(String args[])
{
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;

mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
Access Modifiers in java
There are two types of modifiers in java: access modifiers and
non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a
data member, method, constructor or class.

There are 4 types of java access modifiers:


private
default
protected
Public

There are many non-access modifiers such as static, abstract,


synchronized, native, volatile, transient etc. Here, we will learn
access modifiers.
1.private access modifier
The private access modifier is accessible only within class.

If you make any class constructor private, you cannot create


the instance of that class from outside the class.
//Program for private access specifier.
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}

public class privatedemo


{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
default access modifier
If you don't use any modifier, it is treated as default by default.
The default modifier is accessible only within package.
Package:
Package is collection of interrelated classes & interfaces.

User defined Packages:

Creating Own Packages:

Syntax:
Package mypackage;
Public class myclass
{
------------------------
------------------------
------------------------
}
Accessing Own Packages:

Syntax:

Import pack1[.pack2][.pack3].classname;

Example:

Import mypackage.*;

Import mypackage.myclass;
Example of default access modifier
In this example,
we have created two packages pack and mypack. We are
accessing the A class from outside its package, since A class is
not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is
default so it cannot be accessed from outside the package.
3.protected Modifier:
The protected access modifier is accessible within package
and outside the package but through inheritance only.
The protected access modifier can be applied on the data
member, method and constructor. It can't be applied on the class.

Example of protected access modifier


In this example, we have created the two packages pack and
mypack. The
A class of pack package is public, so can be accessed from outside
the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through
inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}

Output:Hello
4.public access modifier
The public access modifier is accessible everywhere. It has the widest
scope among all other modifiers.

Example of public access modifier


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

//Output:Hello
Array of Object:
Arrays are capable of storing objects also. For example, we can create an
array of Strings which is a reference type variable. However, using a
String as a reference type to illustrate the concept of array of objects isn't
too appropriate due to the immutability of String objects.
Example:

class Student
{
int marks;
}

An array of objects is created just like an array of primitive type data


items in the following way.

Student[] studentArray = new Student[7];


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.
Default Constructor
A constructor that have no parameter is known as default
constructor.

Syntax of default constructor:


<class_name>(){ }

Rule:
If there is no constructor in a class, compiler
automatically creates a default constructor.
class Rectangle
{
double width;
double height;
Rectangle()
{
width = 10;
height = 10;
}
double area()
{
return width * height;
}
}
public class defaultc
{
public static void main(String args[])
{
Rectangle mybox1 = new Rectangle();
double area;
area = mybox1.area();
System.out.println("Area is " + area);
}
}
Java parameterized constructor
A constructor that have parameters is known as parameterized
constructor.
Parameterized constructor is used to provide different values to
the distinct objects.
class student
{
int rno;
String name;

student(int i,String n)
{
rno = i;
name = n;
}
void display()
{
System.out.println("Rno: "+rno+"\tName: "+name+"\n");
}
}
class pconstruct
{
public static void main(String args[])
{
student s1 = new student(5,"Karan");
student s2 = new student(2,"Aryan");
s1.display();
s2.display();
}
}
Constructor Overloading in Java

❖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
{
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;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}

public static void main(String args[])


{
student s1 = new student(111,"Karan");
student s2 = new student(222,"Aryan",25);
s1.display();
s2.display();
}
}
this keyword in java
There can be a lot of usage of java this keyword. In java, this is a
reference variable that refers to the current object.

Usage of java this keyword


Here is given the 6 usage of java this keyword.
this can be used to refer current class instance variable.
this can be used to invoke current class method (implicitly)
this() can be used to invoke current class constructor.
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this can be used to return the current class instance from the method.
Understanding the problem without this keyword
class student
{
int rno;
String name;
float fee;
student(int rno,String name,float fee)
{
rno=rno;
name=name;
fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class testthis1
{
public static void main(String args[])
{
student s1=new student(111,"ankit",5000f);
student s2=new student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
Solution of the above problem by this keyword
class student
{
int rno;
String name;
float fee;
student(int rno,String name,float fee)
{
this.rno=rno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println("Rno: "+rno+"\tName: "+name+"\tFee:
"+fee);
}
}
class testthis2
{
public static void main(String args[])
{
student s1=new student(111,"ankit",5000f);
student s2=new student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
Java static block
•It is used to initialize the static data member.
It is executed before main method at the time of classloading.

class staticblk
{
static
{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}
Java static method

If you apply static keyword with any method, it is known as static


method.

•A static method belongs to the class rather than object of a class.

•A static method can be invoked without the need for creating an instance
of a class.

•static method can access static data member and can change the value of
it.
static Variable:

•If you declare any variable as static, it is known static variable.

•The static variable can be used to refer the common property of all
objects
e.g. company name of employees,college name of students etc.

•The static variable gets memory only once in class area at the time of
class loading.
class staticstud
{
int rno;
String name;
static String college = "PCMCS";

static void change()


{
college = "ACBCS";
}
staticstud(int r, String n)
{
rno = r;
name = n;
}
void display ()
{
System.out.println(rno+" "+name+" "+college);
}

public static void main(String args[])


{
staticstud.change();

staticstud s1 = new staticstud(111,"Atharv");


staticstud s2 = new staticstud(222,"Aarya");
staticstud s3 = new staticstud(333,"Monu");

s1.display();
s2.display();
s3.display();
}
}
The finalize() method :

Finalize() is the method of Object class.

This method is called just before an object is garbage collected. It


performs clean-up activity.

Clean-up activity means closing the resources associated with that object
like Database Connection, Network Connection or we can say resource
de-allocation.

Once the finalize method completes immediately Garbage Collector


destroy that object.

Syntax:
protected void finalize() throws Throwable{}
Nested Class:

In Java, it is possible to define a class within another class, such


classes are known as nested classes.

Nested classes are divided into two categories:

static nested class : Nested classes that are declared static are called
static nested classes.

Non-static nested class(inner class) : An inner class is a non-static


nested class.
Syntax:
class OuterClass
{ ...

class NestedClass
{ ...

}
}
Method Overloading in java

If a class has multiple methods having same name but different in


parameters, it is known as Method Overloading.
Recursion in Java
Recursion in java is a process in which a method calls itself continuously.

A method in java that calls itself is called recursive method.

It makes the code compact but complex to understand.

Syntax:
returntype methodname()
{
//code to be executed
methodname();//calling same method
}
Anonymous Inner Class

It is an inner class without a name and for which only a single object is
created.

An anonymous inner class can be useful when making an instance of


an object with certain “extras” such as overloading methods of a class
or interface, without having to actually subclass a class.

Anonymous inner classes are useful in writing implementation classes


for listener interfaces in graphics programming.

Anonymous inner class are mainly created in two ways:


Class (may be abstract or concrete)
Interface
Object class in Java

•The Object class is the parent class of all the classes in java by
default.
• In other words, it is the topmost class of java.

•The Object class is beneficial if you want to refer any object whose
type you don't know. Notice that parent class reference variable can
refer the child class object, know as upcasting.

•Let's take an example, there is getObject() method that returns an


object but it can be of any type like Employee,Student etc, we can
use Object class reference to refer that object.

• For example:
•Object obj=getObject();//we don't know what object will be returne
d from this method

You might also like