Upload
bhuvijayavelu
View
46
Download
1
Embed Size (px)
Citation preview
JAVA - CLASSES & OBJECTS
OBJECTIVES Java must be encapsulated in a class that defines the “state” and
“behaviour” of the basic program components known as objects.
Classes - a convenient way of grouping logically related data items
and functions that work on them. The data item called as field and
functions are called as methods.
Classes create objects and objects use methods to communicate
between them.
Class Definition
A class contains a name, several variable declarations (instance variables)
and several method declarations. All are called members of the class.
General form of a class:
class classname [extends superclass_name]
{
type instance-variable-1;
type instance-variable-n
type method-name-1(parameter-list) { … }
type method-name-2(parameter-list) { … }
type method-name-m(parameter-list) { … }
}
Classes A class is a collection of fields (data) and methods (procedure or
function) that operate on that data. The fields (data) are also called the instance varaibles. Instance variable
A variable that is created inside the class but outside the method, is known as instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when object(instance) is created. That is why, it is known as instance variable.
Circle
centreradius
circumference()area()
The basic syntax for a class definition:
class ClassName [extends SuperClassName]
{
[fields declaration] // data field
[methods declaration] // method
}
Bare bone class – no fields, no methods
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;}
Object:A runtime entity that has state and behaviour is known as an
object.
An object has three characterstics:
state: represents the data of an object.
behaviour: represents the behaviour of an object.
identity: Object identity is typically implemented via a unique ID.
The value of the ID is not visible to the external user, but is used
internally by the JVM to identify each object uniquely.
What are the different ways to create an object in Java?
new keyword
newInstance() method
clone() method
factory method etc.
Creating objects of a class Object – block of memory that contains space to store all instance
variables. Objects are created dynamically using the new keyword. It’s called
instantiating an object. Example:
class_name object_name;object_name=new class_name();
orclass_name object_name=new class_name();
Object’s created:
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
Constructor in JavaConstructor is a special type of method that is used to initialize the
object.
Constructor is invoked at the time of object creation.
Rules for creating constructor
Constructor name must be same as its class name
Constructor must have no explicit return type
Types of constructors
default constructor (no-arg constructor) - constructor that have no
parameter is known as default constructor. Default values to the
object like 0, null etc. depending on the type.<class_name>(){}
parameterized constructor - A constructor that have parameters is
known as parameterized constructor. Used to provide different
values to the distinct objects. <class_name>(parameter list){}
class Student{ int id; String name; void display(){System.out.println(id+" "+name);}public static void main(String args[]){ Student s1=new Student(); Student s2=new Student(); s1.display(); s2.display(); } }
class Student{ int id; String name; Student(int i,String n){ id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); s1.display(); s2.display(); } }
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.
Method Overloading
class have multiple methods by same name but different
parameters, it is known as Method Overloading.
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();}}
Constructor Overloading
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);}}
Method Overloading
What is the difference between constructor and method ?
Constructor Method
Constructor is used to initialize the state of an object.
Method is used to expose behaviour of an object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default constructor if you don't have any constructor.
Method is not provided by compiler in any case.
Constructor name must be same as the class name.
Method name may or may not be same as class name.
STATIC KEYWORD
class class_name{public static void main(String args[]){data / field / instance variables;methods / instance methods;}}Object creation – class_name object_name=new class_name();
object_name.variables;object_name.methods();
Every time class instantiated / object created a new copy of each of variable and methods are created.Then accessed with (.) operator.
Define a member that is common to all object not to specific object.
Static variables – called as class variable
Static methods – called as class methods
static variable:
declare any variable as static, it is known static variable.
static method:
static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class.
invoked without the need for creating an instance of a class.
access static data member and can change the value of it.
Final Keyword In Java
The final keyword in java is used to restrict the user.
Generally all the variables / methods by default overridden in subclasses
Final – to prevent the subclass from overriding the members of
superclass.
The final keyword can be used in many context. Final can be:
Variable - make any variable as final, you cannot change the value of
final variable(It will be constant).
Method - make any method as final, you cannot override it.
Class - make any method as final, you cannot override it.
class Bike{final int speedlimit=90;//final variablevoid run(){speedlimit=400;}public static void main(String args[]){Bike obj=new Bike();obj.run();}}//end of class
class Bike{final void run(){System.out.println("running");}}class Honda extends Bike{void run(){System.out.println("running safely");}public static void main(String args[]){Honda honda= new Honda();honda.run();}}
final class Bike{}class Honda extends Bike{void run(){System.out.println("running safely with 100kmph");}public static void main(String args[]){Honda honda= new Honda();honda.run();}}
Finalizer methods:
Constructor – used to initialize an object when it’s declared – initialization
Automatic garbage collection
run time, It’s frees up the memory resources used by objects.
But objects still hold – non object resources
Garbage collector – can’t free those resources
use finalizer method like desctructor.
Syntax:
finalize()
Abstract keyword
Opposite to final – make use of the same method name in subclass
Overridden is compulsory.
Abstract class in Java
class that is declared with abstract keyword, is known as abstract classabstract class <class_name>{}
abstract method
method that is declared as abstract - abstract method
does not have implementation, it’s in derived class
abstract return_type <method_name>();//no braces{}
abstract class Bike // abstract class{abstract void run(); // abstract method}class Honda extends Bike{void run(){System.out.println("running safely..");}public static void main(String args[]){Bike obj = new Honda();obj.run();}}