SlideShare a Scribd company logo
OOP
OOP as a methodology that organizes a programinto a collection of interacting
objects. A more technical definition asserts that OOP is a programming paradigm
that incorporates the principles of encapsulation , inheritance , and
polymorphism.
ClassesandObjectsinJava
ClassesandObjectsare basicconceptsof ObjectOrientedProgrammingwhichrevolvearoundthe real
life entities.
Class
A classis a userdefinedblueprintorprototype fromwhichobjectsare created. Itrepresentsthe setof
propertiesormethodsthatare commonto all objectsof one type.Ingeneral,classdeclarationscan
include these components,inorder:
Modifiers:A class can be publicor has defaultaccess(Refer this for details).
Class name: The name shouldbeginwithaninitialletter(capitalizedbyconvention).
Superclass(if any):The name of the class’sparent(superclass),if any,precededbythe keyword
extends.A classcan onlyextend(subclass)one parent.
Interfaces(if any): A comma-separatedlistof interfacesimplementedbythe class,if any,precededby
the keywordimplements.A classcan implementmore thanone interface.
Body:The classbody surroundedbybraces,{ }.
Constructorsare usedforinitializingnew objects.Fieldsare variablesthatprovidesthe state of the class
and itsobjects,andmethodsare usedto implementthe behaviorof the classanditsobjects.
There are varioustypesof classesthatare usedinreal time applicationssuchas nested
classes,anonymous classes,lambda expressions.
Object
It isa basicunitof ObjectOrientedProgramming andrepresentsthe real lifeentities. A typical Java
program createsmanyobjects,whichasyouknow,interactby invokingmethods.Anobjectconsistsof :
State :It is representedbyattributesof anobject.Italsoreflectsthe propertiesof anobject.
Behavior :It is representedbymethodsof anobject.Italsoreflectsthe response of anobjectwith
otherobjects.
Identity :It givesa unique name toanobjectand enablesone objecttointeractwith otherobjects.
Example of an object:dog
Objectscorrespondtothingsfoundinthe real world.Forexample,agraphicsprogrammay have objects
such as “circle”,“square”,“menu”.Anonline shoppingsystemmighthave objectssuchas“shopping
cart”, “customer”,and “product”.
Declaring Objects(Alsocalledinstantiating a class)
Whenan objectof a classis created,the classissaidto be instantiated.All the instancesshare the
attributesandthe behaviorof the class.But the valuesof those attributes,i.e.the state are unique for
each object.A single classmayhave anynumberof instances.
As we declare variableslike (type name;).Thisnotifiesthe compilerthatwe will use name toreferto
data whose type istype.Witha primitive variable,thisdeclarationalsoreservesthe properamountof
memoryforthe variable.Soforreference variable, type mustbe strictlyaconcrete classname.In
general,we can’tcreate objectsof anabstract class or an interface.
Dog tuffy;
If we declare reference variable(tuffy) like this,itsvalue willbe undetermined(null) until anobjectis
actuallycreatedandassignedtoit.Simplydeclaringa reference variable doesnotcreate anobject.
Initializingan object
The newoperatorinstantiatesaclassby allocatingmemoryforanew objectand returningareference
to that memory.The newoperatoralsoinvokesthe class constructor.
What are Methods?
A methodisa setof code whichisreferredtoby name and can be called(invoked) atanypointina
program simplybyutilizingthe method'sname. Thinkof a methodasa subprogramthat acts on data
and oftenreturnsavalue.
Each methodhas itsownname. Whenthat name is encounteredinaprogram, the executionof the
program branchestothe bodyof that method. Whenthe methodisfinished,executionreturnstothe
area of the programcode from whichitwas called,andthe programcontinuesonto the nextline of
code.
Good programmerswrite ina modularfashionwhichallowsforseveral programmerstowork
independentlyonseparate conceptswhichcanbe assembledata laterdate to create the entire
project. The use of methodswill be ourfirststepinthe directionof modularprogramming.
Methodsare time savers,inthattheyallow forthe repetitionof sectionsof code withoutretypingthe
code. In addition,methodscanbe savedandutilizedagainandagaininnewlydevelopedprograms.
You are usingmethods whenyouuse
System.out.print( ) andSystem.out.println( ).
There are twobasictypesof methods:
Built-in: Build-inmethodsare partof the compilerpackage,suchas System.out.println(
) and System.exit(0).
User-defined:User-definedmethodsare createdbyyou,the programmer.These methods
take-onnamesthatyouassignto themand performtasksthat youcreate.
How to invoke (call) a method (methodinvocation):
Whena methodisinvoked(called),arequestismade toperformsome action,suchas settingavalue,
printingstatements,returningananswer,etc. The code to invoke the methodcontainsthe name of the
methodtobe executedandanyneededdatathatthe receivingmethodrequires. The requireddatafor
a methodare specified inthe method'sparameterlist.
Considerthismethodthatwe have alreadybeenusingfromBreezy;
intnumber= Console.readInt("Enteranumber"); //returnsavalue
The methodname is"readInt"whichisdefinedinthe class"Console". Since the methodisdefinedin
the class Console,the word Consolebecomesthe callingobject. Thisparticularmethodreturnsan
integervalue whichisassignedtoanintegervariable named number.
You invoke (call) amethodbywritingdownthe callingobjectfollowed byadot,thenthe name of the
method,andfinallyasetof parenthesesthatmay(ormay not) have informationforthe method.A Java
methodisa collectionof statementsthatare groupedtogethertoperformanoperation.Whenyoucall
the System.out.println() method,forexample,the systemactuallyexecutesseveral statementsinorder
to displayamessage onthe console.
Nowyouwill learnhowtocreate yourownmethodswithorwithoutreturnvalues,invokeamethod
withor withoutparameters,andapplymethodabstractioninthe programdesign.
CreatingMethod
Consideringthe followingexample toexplainthe syntax of amethod−
Syntax
publicstaticintmethodName(inta,intb) {
// body
}
Here,
publicstatic − modifier
int − returntype
methodName − name of the method
a, b − formal parameters
int a, int b − listof parameters
Methoddefinitionconsistsof amethodheaderanda methodbody.The same isshowninthe following
syntax −
Syntax
modifierreturnType nameOfMethod(ParameterList) {
// methodbody
}
The syntax shownabove includes−
modifier− It definesthe accesstype of the methodanditis optional touse.
returnType − Methodmay returna value.
nameOfMethod− Thisis the methodname.The methodsignature consistsof the methodname and the
parameterlist.
Parameter List − The listof parameters,itisthe type,order,and numberof parametersof a method.
These are optional,methodmaycontainzeroparameters.
methodbody − The methodbodydefineswhatthe methoddoeswiththe statements.
Example
Here is the source code of the above definedmethodcalled min().Thismethodtakestwoparameters
num1 and num2 andreturnsthe maximumbetweenthe two−
/** the snippetreturnsthe minimumbetweentwonumbers*/
publicstaticintminFunction(intn1,intn2) {
intmin;
if (n1 > n2)
min= n2;
else
min= n1;
returnmin;
}
MethodCalling
For usinga method,itshouldbe called.There are twowaysinwhicha methodiscalledi.e.,method
returnsa value or returningnothing (noreturnvalue).
The processof methodcallingissimple.Whenaprograminvokesamethod,the programcontrol gets
transferredtothe calledmethod.Thiscalledmethodthenreturnscontrol tothe callerintwoconditions,
when−
the returnstatementis executed.
it reachesthe methodendingclosingbrace.
The methodsreturningvoidisconsideredascall to a statement.Letsconsideranexample−
System.out.println("Thisistutorialspoint.com!");
The methodreturningvalue canbe understoodbythe followingexample−
intresult= sum(6,9);
Followingisthe example todemonstrate how todefineamethodandhow to call it −
Example
Live Demo
publicclassExampleMinNumber{
publicstaticvoidmain(String[] args) {
inta = 11;
intb = 6;
intc = minFunction(a,b);
System.out.println("MinimumValue=" + c);
}
/** returnsthe minimumof twonumbers*/
publicstaticintminFunction(intn1,intn2) {
intmin;
if (n1 > n2)
min= n2;
else
min= n1;
returnmin;
}
}
Thiswill produce the followingresult−
Output
Minimumvalue =6
ThevoidKeyword
The voidkeywordallowsustocreate methodswhichdonot returna value.Here,in the following
example we're consideringavoidmethod methodRankPoints.Thismethodisavoidmethod,whichdoes
not returnany value.Call toa voidmethodmustbe a statementi.e. methodRankPoints(255.7);.Itis a
Java statementwhichendswitha semicolonasshowninthe followingexample.
Example
Live Demo
publicclassExampleVoid{
publicstaticvoidmain(String[] args) {
methodRankPoints(255.7);
}
publicstaticvoidmethodRankPoints(doublepoints){
if (points>= 202.5) {
System.out.println("Rank:A1");
}else if (points>=122.4) {
System.out.println("Rank:A2");
}else {
System.out.println("Rank:A3");
}
}
}
Thiswill produce the followingresult−
Output
Rank:A1
PassingParametersbyValue
While workingundercallingprocess,argumentsistobe passed.These shouldbe inthe same orderas
theirrespective parametersinthe methodspecification.Parameterscanbe passedbyvalue or by
reference.
PassingParametersbyValue meanscallingamethodwithaparameter.Throughthis,the argument
value ispassedtothe parameter.
Example
The followingprogramshowsanexample of passingparameterbyvalue.The valuesof the arguments
remainsthe same evenafterthe methodinvocation.
Live Demo
publicclassswappingExample{
publicstaticvoidmain(String[] args) {
inta = 30;
intb = 45;
System.out.println("Before swapping,a= " + a + " and b = " + b);
// Invoke the swapmethod
swapFunction(a,b);
System.out.println("n**Now,Before andAfterswappingvalueswillbe same here**:");
System.out.println("Afterswapping,a= " + a + " and b is" + b);
}
publicstaticvoidswapFunction(inta,intb) {
System.out.println("Before swapping(Inside),a= " + a + " b = " + b);
// Swapn1 withn2
intc = a;
a = b;
b = c;
System.out.println("Afterswapping(Inside),a= " + a + " b = " + b);
}
}
Thiswill produce the followingresult−
Output
Before swapping,a= 30 and b = 45
Before swapping(Inside),a= 30 b = 45
Afterswapping(Inside),a= 45 b = 30
**Now,Before andAfterswappingvalueswill be same here**:
Afterswapping,a= 30 and b is 45
MethodOverloading
Whena class has twoor more methodsbythe same name butdifferentparameters,itisknownas
methodoverloading.Itisdifferentfromoverriding.Inoverriding,amethodhasthe same methodname,
type,numberof parameters,etc.
Let’sconsiderthe example discussedearlierforfindingminimumnumbersof integertype.If,let’ssay
we want to findthe minimumnumberof double type.Thenthe conceptof overloadingwillbe
introducedtocreate twoor more methodswiththe same name butdifferentparameters.
The followingexample explainsthe same −
Example
Live Demo
publicclassExampleOverloading{
publicstaticvoidmain(String[] args) {
inta = 11;
intb = 6;
double c= 7.3;
double d= 9.4;
intresult1= minFunction(a,b);
// same functionname withdifferentparameters
double result2=minFunction(c,d);
System.out.println("MinimumValue=" + result1);
System.out.println("MinimumValue=" + result2);
}
// forinteger
publicstaticintminFunction(intn1,intn2) {
intmin;
if (n1 > n2)
min= n2;
else
min= n1;
returnmin;
}
// fordouble
publicstaticdouble minFunction(double n1,double n2) {
double min;
if (n1 > n2)
min= n2;
else
min= n1;
returnmin;
}
}
Thiswill produce the followingresult−
Output
MinimumValue =6
MinimumValue =7.3
Overloadingmethodsmakesprogramreadable.Here,twomethodsare givenbythe same name but
withdifferentparameters.The minimumnumberfromintegeranddouble typesisthe result.
UsingCommand-LineArguments
Sometimesyouwill wanttopasssome informationintoaprogramwhenyourun it.This isaccomplished
by passingcommand-line argumentstomain( ).
A command-lineargumentisthe informationthatdirectlyfollowsthe program'sname onthe command
line whenitisexecuted.Toaccessthe command-line argumentsinside aJavaprogramis quite easy.
Theyare storedas stringsinthe Stringarray passedto main( ).
Example
The followingprogramdisplaysall of the command-lineargumentsthatitiscalledwith−
publicclassCommandLine {
publicstaticvoidmain(Stringargs[]){
for(inti = 0; i<args.length;i++) {
System.out.println("args["+i + "]: " + args[i]);
}
}
}
Try executingthisprogramasshownhere −
$java CommandLine thisisacommandline 200 -100
Thiswill produce the followingresult−
Output
args[0]:this
args[1]:is
args[2]:a
args[3]:command
args[4]:line
args[5]:200
args[6]:-100
Thethiskeyword
this isa keywordinJavawhichisusedas a reference tothe objectof the currentclass,withinan
instance methodora constructor.Using this youcan referthe membersof a classsuch as constructors,
variables andmethods.
Note − The keyword thisis usedonlywithininstancemethodsorconstructors
In general,the keyword thisisusedto−
Differentiate the instance variablesfromlocal variablesif theyhave same names,withinaconstructoror
a method.
classStudent{
intage;
Student(intage) {
this.age = age;
}
}
Call one type of constructor (parametrizedconstructorordefault) fromotherinaclass.It isknownas
explicitconstructorinvocation.
classStudent{
intage
Student() {
this(20);
}
Student(intage) {
this.age = age;
}
}
Example
Here is an example thatuses thiskeywordtoaccessthe membersof a class.Copyand paste the
followingprogramina file withthe name, This_Example.java.
Live Demo
publicclassThis_Example {
// Instance variable num
intnum = 10;
This_Example() {
System.out.println("Thisisanexample programonkeywordthis");
}
This_Example(intnum) {
// Invokingthe defaultconstructor
this();
// Assigningthe local variable numtothe instance variablenum
this.num=num;
}
publicvoidgreet() {
System.out.println("Hi Welcome toTutorialspoint");
}
publicvoidprint() {
// Local variable num
intnum = 20;
// Printingthe local variable
System.out.println("valueof local variable numis:"+num);
// Printingthe instance variable
System.out.println("valueof instance variable numis:"+this.num);
// Invokingthe greetmethodof aclass
this.greet();
}
publicstaticvoidmain(String[] args) {
// Instantiatingthe class
This_Example obj1=newThis_Example();
// Invokingthe printmethod
obj1.print();
// Passinganewvalue tothe numvariable throughparametrizedconstructor
This_Example obj2=newThis_Example(30);
// Invokingthe printmethodagain
obj2.print();
}
}
Thiswill produce the followingresult−
Output
Thisis an example programonkeywordthis
value of local variable numis: 20
value of instance variable numis:10
Hi Welcome toTutorialspoint
Thisis an example programonkeywordthis
value of local variable numis: 20
value of instance variable numis:30
Hi Welcome toTutorialspoint
VariableArguments(var-args)
JDK 1.5 enablesyoutopassa variable numberof argumentsof the same type to a method.The
parameterinthe methodisdeclaredasfollows−
typeName...parameterName
In the methoddeclaration,youspecifythe type followedbyanellipsis(...).Onlyone variable-length
parametermaybe specifiedinamethod,andthisparametermust be the last parameter.Anyregular
parametersmustprecede it.
Example
Live Demo
publicclassVarargsDemo{
publicstaticvoidmain(Stringargs[]){
// Call methodwithvariable args
printMax(34,3, 3, 2, 56.5);
printMax(newdouble[]{1,2,3});
}
publicstaticvoidprintMax( double...numbers) {
if (numbers.length==0) {
System.out.println("Noargumentpassed");
return;
}
double result =numbers[0];
for (inti = 1; i < numbers.length;i++)
if (numbers[i] > result)
result= numbers[i];
System.out.println("Themax value is"+ result);
}
}
Thiswill produce the followingresult−
Output
The max value is56.5
The max value is3.0
Thefinalize()Method
It ispossible todefineamethodthatwill be calledjustbefore anobject'sfinal destructionbythe
garbage collector.Thismethodiscalled finalize( ),anditcan be usedto ensure thatan object
terminates cleanly.
For example,youmightuse finalize() tomake sure that an openfile ownedbythatobjectisclosed.
To add a finalizertoaclass, yousimplydefine the finalize() method.The Javaruntime callsthatmethod
wheneveritisaboutto recycle an objectof that class.
Inside the finalize() method,youwillspecifythose actionsthatmustbe performedbefore anobjectis
destroyed.
The finalize( ) methodhasthisgeneral form−
protectedvoidfinalize( ) {
// finalizationcode here
}
Here,the keywordprotectedisaspecifierthatpreventsaccesstofinalize() bycode definedoutside its
class.
FINAL VARIABLES
A final variable is a variable that is assigned a permanent value.
A final variable may be assigned a value justonce in any program, and once
assigned, the value cannot be altered. Its value is, well, “final.” In Example 3.5, the
value 3.14159 is thevalue 3.14159 is assigned to PI as partof the declaration. It
is a good practice to initialize a final variable when it is declared. By
convention, names of final variables arecomprised of uppercaseletters with
underscores separating the“words” of a name. For example, PI, TAX_RATE and
FIDDLE_DEE_DEE adhere to this practice
area PI *radius*radius,
Thismeansthat youcannot knowwhenor evenif finalize( ) will be executed.Forexample,if your
program endsbefore garbage collectionoccurs,finalize( ) willnotexecute.
String Concatenation
. For example,the statement
System.out.println("Frankenstein" "meets"
"Dracula"); effectsthe concatenationof three strings:"Frankenstein","
meets",and "Dracula".
Concatenation is the process of joining, connecting, or linking Strings together.
What is Abstraction
Abstractionisa processof hidingthe implementationdetailsfromthe user.Оnlythe functionalitywill
be providedtothe user. In Java,abstractionisachievedusingabstractclassesandinterfaces.We have a
more detailedexplanationonJavaInterfaces,if youneedmore infoaboutInterfaces pleasereadthis
tutorial first.
Abstractionisone of the fourmajorconceptsbehind object-orientedprogramming(OOP).OOP
questionsare verycommoninjobinterviews,soyoumayexpectquestionsaboutabstractiononyour
nextJavajob interview.
AbstractClassin Java
Abstractclass inJava issimilartointerface exceptthatitcan containdefaultmethodimplementation.
An abstractclass can have an abstract methodwithoutbodyanditcan have methodswith
implementationalso.
abstract keywordisusedtocreate an abstract class and method.Abstractclassinjavacan’t be
instantiated.Anabstractclassismostlyusedtoprovide abase for subclassestoextendandimplement
the abstract methodsandoverride oruse the implementedmethodsinabstractclass.
package com.journaldev.design;
//abstractclass
publicabstractclass Person{
private Stringname;
private Stringgender;
publicPerson(Stringnm,Stringgen){
this.name=nm;
this.gender=gen;
}
//abstractmethod
publicabstractvoidwork();
@Override
publicStringtoString(){
return"Name="+this.name+"::Gender="+this.gender;
}
publicvoidchangeName(StringnewName) {
this.name =newName;
}
}
Notice thatwork() isan abstract methodand ithas no-body.Here isa concrete classexample extending
an abstract classin java.
package com.journaldev.design;
publicclassEmployee extendsPerson{
private intempId;
publicEmployee(Stringnm,Stringgen,intid) {
super(nm,gen);
this.empId=id;
}
@Override
publicvoidwork() {
if(empId==0){
System.out.println("Notworking");
}else{
System.out.println("Workingasemployee!!");
}
}
publicstaticvoidmain(Stringargs[]){
//codingintermsof abstract classes
Personstudent=newEmployee("Dove","Female",0);
Personemployee =newEmployee("Pankaj","Male",123);
student.work();
employee.work();
//usingmethodimplementedinabstractclass - inheritance
employee.changeName("Pankaj Kumar");
System.out.println(employee.toString());
}
}
Note that subclassEmployeeinheritsthe propertiesandmethodsof superclassPerson
usinginheritance in java.
Abstractclass inJava ImportantPoints
abstract keywordisusedto create an abstract classin java.
Abstractclass injava can’t be instantiated.
We can use abstract keywordtocreate an abstract method,anabstract methoddoesn’thave body.
If a classhave abstract methods,thenthe classshouldalsobe abstractusingabstract keyword,else it
will notcompile.
It’snot necessaryforan abstract classto have abstract method.We can mark a class as abstract evenif
it doesn’tdeclare anyabstractmethods.
If abstract class doesn’thave anymethodimplementation,itsbettertouse interface because java
doesn’tsupportmultiple classinheritance.
The subclassof abstract classinjava mustimplementall the abstractmethodsunlessthe subclassisalso
an abstract class.
All the methodsinaninterface are implicitlyabstractunlessthe interface methodsare staticor default.
Staticmethodsanddefaultmethodsininterfacesare addedin Java 8, formore detailsread Java 8
interface changes.
Java Abstractclass can implementinterfaceswithoutevenprovidingthe implementationof interface
methods.
Java Abstractclass isusedto provide commonmethodimplementationtoall the subclassesorto
provide defaultimplementation.
We can run abstract classin javalike anyotherclassif it has main() method.
Why we needanabstract class?
Letssay we have a class Animal that hasa method sound() and the subclasses(see inheritance) of it
like Dog, Lion, Horse, Cat etc. Since the animal sounddiffersfromone animal toanother,there isno
pointto implementthismethodinparentclass. Thisisbecause everychildclassmustoverride this
methodtogive itsownimplementationdetails,like Lionclasswill say“Roar” in thismethod
and Dog classwill say“Woof”.
So whenwe knowthatall the animal childclasseswill andshouldoverride thismethod,thenthere isno
pointto implementthismethodinparentclass.Thus,makingthismethodabstractwouldbe the good
choice as by makingthismethodabstractwe force all the sub classestoimplementthismethod(
otherwise youwillgetcompilationerror),alsowe neednottogive anyimplementationtothismethod
inparentclass.
Since the Animal classhas an abstract method,youmustneedtodeclare thisclassabstract.
Noweach animal musthave a sound,bymakingthismethodabstractwe made it compulsorytothe
childclassto give implementationdetailstothismethod.Thiswaywe ensuresthateveryanimal hasa
sound.
Abstractclass Example
//abstract parent class
abstract class Animal{
//abstract method
public abstract void sound();
}
//Dog class extends Animal class
public class Dog extends Animal{
public void sound(){
System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();
obj.sound();
}
}
Output:
Woof
Hence for suchkindof scenarioswe generallydeclarethe classasabstract and later concrete
classes extendthese classesandoverride the methodsaccordinglyandcanhave theirownmethodsas
well.
Abstractclass declaration
An abstractclass outlinesthe methodsbutnotnecessarilyimplementsall the methods.
//Declaration using abstract keyword
abstract class A{
//This is abstract method
abstract void myMethod();
//This is concrete method with body
void anotherMethod(){
//Does something
}
}
What is the difference between up-casting and down-casting with respect to class variable
What isthe difference betweenup-castinganddown-castingwithrespecttoclassvariable?
For example inthe followingprogramclassAnimal containsonlyone methodbutDogclasscontainstwo
methods,thenhowwe castthe Dog variable tothe Animal Variable.
If casting isdone thenhowcan we call the Dog's anothermethodwithAnimal'svariable.
classAnimal
{
publicvoidcallme()
{
System.out.println("Incallme of Animal");
}
}
classDog extends Animal
{
publicvoidcallme()
{
System.out.println("Incallme of Dog");
}
publicvoidcallme2()
{
System.out.println("Incallme2of Dog");
}
}
publicclassUseAnimlas
{
publicstaticvoidmain(String[] args)
{
Dog d = new Dog();
Animal a= (Animal)d;
d.callme();
a.callme();
((Dog) a).callme2();
}
}
Upcastingis castingto a supertype,while downcastingiscastingtoa subtype.Upcastingisalways
allowed,butdowncasting involvesatype checkand can throw a ClassCastException.
In yourcase,a cast froma Dog to an Animal isanupcast, because aDog is-aAnimal.Ingeneral,youcan
upcast wheneverthere isanis-arelationshipbetweentwoclasses.
Downcastingwouldbe somethinglikethis:
Animal animal =new Dog();
Dog castedDog= (Dog) animal;
Basicallywhatyou're doingistellingthe compilerthatyouknow whatthe runtime type of the
objectreally is.The compilerwillallow the conversion,butwill still inserta runtime sanitycheckto
make sure that the conversionmakessense.Inthiscase,the cast ispossible because atruntime animalis
actuallya Dog eventhoughthe statictype of animal isAnimal.
However,if youwere todo this:
Animal animal =new Animal();
Dog notADog= (Dog) animal;
You'd geta ClassCastException.The reasonwhyisbecause animal'sruntimetype is Animal,andsowhen
youtell the runtime toperformthe cast it seesthat animal isn'treallyaDog and so throws
a ClassCastException.
To call a superclass'smethodyoucando super.method() orbyperformingthe upcast.
To call a subclass'smethodyouhave todo a downcast.Asshownabove,younormallyrisk
a ClassCastException bydoingthis;however,youcanuse the instanceof operatortocheck the runtime
type of the objectbefore performingthe cast,whichallowsyoutoprevent ClassCastExceptions:
Animal animal =getAnimal();//Maybe a Dog?Maybe a Cat? Maybe an Animal?
if (animal instanceof Dog) {
// Guaranteed tosucceed, barringclassloadershenanigans
Dog castedDog= (Dog) animal;
}
Down-castingandup-castingwasasfollows:
Upcasting:Whenwe want to cast a Sub classto Superclass,we use Upcasting(orwidening).Ithappens
automatically,noneedtodoanything explicitly.
Downcasting :When we wantto cast a Superclassto Subclass,we use Downcasting(ornarrowing),
and Downcastingisnotdirectlypossible inJava,explicitlywe have todo.
Dog d = new Dog();
Animal a = (Animal) d; //Explicitly you have done upcasting. Actually no need, we can directly
type cast like Animal a = d; compiler now treat Dog as Animal but still it is Dog even after
upcasting
d.callme();
a.callme(); // It calls Dog's method even though we use Animal reference.
((Dog) a).callme2(); // Downcasting: Compiler does know Animal it is, In order to use Dog
methods, we have to do typecast explicitly.
// Internally if it is not a Dog object it throws ClassCastException
Upcastingand downcastingare importantpartof Java,whichallow usto buildcomplicatedprograms
usingsimple syntax,andgivesusgreatadvantages,like Polymorphismorgroupingdifferent
objects. Javapermitsan object of a subclasstype to be treated asan object of any superclass type.
This iscalled upcasting.Upcastingisdoneautomatically, whiledowncasting mustbemanuallydone
by the programmer, andi'm goingto give mybestto explainwhyisthatso.
Upcastingand downcastingare NOTlike castingprimitivesfromone toother,andi believe that'swhat
causesa lot of confusion,whenprogrammerstartstolearncastingobjects.
Polymorphism:All methodsinjava are virtual by default.That means that any methodcan be
overridden whenused in inheritance, unlessthat method isdeclared as final or static.
You can see the example belowhow getType();worksaccordingtothe object(Dog,Pet,Police Dog) type.
Assume youhave three dogs
Dog - Thisis the superClass.
PetDog - PetDog extendsDog.
Police Dog- Police DogextendsPetDog.
publicclassDog{
publicStringgetType () {
System.out.println("NormalDog");
return"NormalDog";
}
}
/**
* PetDog has an extramethoddogName()
*/
publicclassPetDogextends Dog{
publicStringgetType () {
System.out.println("PetDog");
return"PetDog";
}
publicStringdogName () {
System.out.println("Idon'thave Name !!");
return"NOName";
}
}
/**
* Police Doghas an extramethodsecretId()
*/
publicclassPoliceDogextends PetDog{
publicStringsecretId() {
System.out.println("ID");
return"ID";
}
publicStringgetType () {
System.out.println("IamaPolice Dog");
return"Police Dog";
}
}
Polymorphism:All methodsinjavaare virtual bydefault.Thatmeansthat anymethodcan be
overriddenwhenusedininheritance,unlessthatmethodisdeclaredasfinal orstatic.(Explanation
BelongstoVirtual TablesConcept)
public static void main (String[] args) {
/**
* Creating the different objects with super class Reference
*/
Dog obj1 = new Dog();
` /**
* Object of Pet Dog is created with Dog Reference since
* Upcasting is done automatically for us we don't have to worry about it
*
*/
Dog obj2 = new PetDog();
` /**
* Object of Police Dog is created with Dog Reference since
* Upcasting is done automatically for us we don't have to worry
* about it here even though we are extending PoliceDog with PetDog
* since PetDog is extending Dog Java automatically upcast for us
*/
Dog obj3 = new PoliceDog();
}
obj1.getType();
PrintsNormal Dog
obj2.getType();
PrintsPet Dog
obj3.getType();
PrintsPolice Dog
Downcasting need to be done by the programmer manually
Whenyoutry to invoke the secretID(); methodon obj3 whichis PoliceDog object but referenced
to Dog whichisa superclassinthe hierarchyitthrowserrorsince obj3 don't have access
to secretId() method.In order to invoke that method you need to Downcast that obj3 manually
toPoliceDog
( (PoliceDog)obj3).secretID();
whichprintsID
In the similarwaytoinvoke the dogName();methodin PetDog classyou needto
downcastobj2 to PetDog since obj2isreferencedto Dog and don't have access
to dogName(); method
( (PetDog)obj2).dogName();
Why isthat so,that upcastingis automatical,butdowncastingmustbe manual?Well,yousee,upcasting
can neverfail.Butif youhave a groupof differentDogsandwantto downcastthemall to a to their
types,thenthere'sachance,that some of these Dogsare actuallyof differenttypes
i.e., PetDog,PoliceDog, and processfails,bythrowing ClassCastException.
Thisis the reasonyouneedto downcast your objects manually if you have referencedyourobjects
to the superclass type.

More Related Content

PDF
Architecture of a morphological malware detector
UltraUploader
 
PPTX
Java method
sunilchute1
 
PPTX
Object oriented programming in python
nitamhaske
 
PDF
Object Oriented Programming Lab Manual
Abdul Hannan
 
DOC
Faqs in java
prathap kumar
 
PDF
Implementation
adil raja
 
PDF
ASE02.ppt
Ptidej Team
 
ODP
Method Handles in Java
hendersk
 
Architecture of a morphological malware detector
UltraUploader
 
Java method
sunilchute1
 
Object oriented programming in python
nitamhaske
 
Object Oriented Programming Lab Manual
Abdul Hannan
 
Faqs in java
prathap kumar
 
Implementation
adil raja
 
ASE02.ppt
Ptidej Team
 
Method Handles in Java
hendersk
 

What's hot (18)

PDF
Oop basic concepts
Swarup Kumar Boro
 
DOCX
core java syllabus
Sabyasachi Mohanty
 
PDF
maXbox Starter 31 Closures
Max Kleiner
 
PDF
Core java interview faq
Kumaran K
 
PPT
Chap03
Terry Yoast
 
PPT
Chap03
Terry Yoast
 
PDF
Object-oriented Programming in Python
Juan-Manuel Gimeno
 
PPTX
Java Method, Static Block
Infoviaan Technologies
 
DOCX
Intervies
roopa manoharan
 
DOCX
Mcs 024 assignment solution (2020-21)
smumbahelp
 
PPT
Java căn bản - Chapter7
Vince Vo
 
PPTX
Java interview questions 1
Sherihan Anver
 
PDF
A Logic Meta-Programming Foundation for Example-Driven Pattern Detection in O...
Coen De Roover
 
KEY
What's New In Python 2.4
Richard Jones
 
DOC
Questions of java
Waseem Wasi
 
PPT
Oo Design And Patterns
Anil Bapat
 
DOC
[PDF]
butest
 
KEY
What's New In Python 2.5
Richard Jones
 
Oop basic concepts
Swarup Kumar Boro
 
core java syllabus
Sabyasachi Mohanty
 
maXbox Starter 31 Closures
Max Kleiner
 
Core java interview faq
Kumaran K
 
Chap03
Terry Yoast
 
Chap03
Terry Yoast
 
Object-oriented Programming in Python
Juan-Manuel Gimeno
 
Java Method, Static Block
Infoviaan Technologies
 
Intervies
roopa manoharan
 
Mcs 024 assignment solution (2020-21)
smumbahelp
 
Java căn bản - Chapter7
Vince Vo
 
Java interview questions 1
Sherihan Anver
 
A Logic Meta-Programming Foundation for Example-Driven Pattern Detection in O...
Coen De Roover
 
What's New In Python 2.4
Richard Jones
 
Questions of java
Waseem Wasi
 
Oo Design And Patterns
Anil Bapat
 
[PDF]
butest
 
What's New In Python 2.5
Richard Jones
 
Ad

Similar to Class (20)

PPTX
OOPSCA1.pptx
Soumyadipchanda2
 
PPTX
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
vekariyakashyap
 
PPTX
Java method present by showrov ahamed
Md Showrov Ahmed
 
PPTX
Basic concept of class, method , command line-argument
Suresh Mohta
 
PPT
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
mcjaya2024
 
PDF
CIS 1403 lab 3 functions and methods in Java
Hamad Odhabi
 
PPT
Explain Classes and methods in java (ch04).ppt
ayaankim007
 
PPT
Core Java unit no. 1 object and class ppt
Mochi263119
 
PPT
Class & Object - User Defined Method
PRN USM
 
DOCX
Methods in Java
Kavitha713564
 
PPTX
Java class,object,method introduction
Sohanur63
 
PPTX
Computer programming 2 Lesson 15
MLG College of Learning, Inc
 
PPTX
Working with Methods in Java.pptx
maryansagsgao
 
PPT
packages and interfaces
madhavi patil
 
PPTX
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
mohanrajm63
 
PPTX
Lecture 5
talha ijaz
 
PPT
Class & Object - Intro
PRN USM
 
PPTX
Chap2 class,objects contd
raksharao
 
PPTX
Lec 1.4 Object Oriented Programming
Badar Waseer
 
PDF
oblect oriented programming language in java notes .pdf
sanraku980
 
OOPSCA1.pptx
Soumyadipchanda2
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
vekariyakashyap
 
Java method present by showrov ahamed
Md Showrov Ahmed
 
Basic concept of class, method , command line-argument
Suresh Mohta
 
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
mcjaya2024
 
CIS 1403 lab 3 functions and methods in Java
Hamad Odhabi
 
Explain Classes and methods in java (ch04).ppt
ayaankim007
 
Core Java unit no. 1 object and class ppt
Mochi263119
 
Class & Object - User Defined Method
PRN USM
 
Methods in Java
Kavitha713564
 
Java class,object,method introduction
Sohanur63
 
Computer programming 2 Lesson 15
MLG College of Learning, Inc
 
Working with Methods in Java.pptx
maryansagsgao
 
packages and interfaces
madhavi patil
 
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
mohanrajm63
 
Lecture 5
talha ijaz
 
Class & Object - Intro
PRN USM
 
Chap2 class,objects contd
raksharao
 
Lec 1.4 Object Oriented Programming
Badar Waseer
 
oblect oriented programming language in java notes .pdf
sanraku980
 
Ad

Recently uploaded (20)

PPTX
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PDF
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
PDF
AI-Driven IoT-Enabled UAV Inspection Framework for Predictive Maintenance and...
ijcncjournal019
 
PPTX
Information Retrieval and Extraction - Module 7
premSankar19
 
PDF
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
PPTX
Tunnel Ventilation System in Kanpur Metro
220105053
 
PPTX
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
PDF
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
PDF
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
PPTX
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
PPTX
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
PPTX
Inventory management chapter in automation and robotics.
atisht0104
 
PDF
All chapters of Strength of materials.ppt
girmabiniyam1234
 
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
AI-Driven IoT-Enabled UAV Inspection Framework for Predictive Maintenance and...
ijcncjournal019
 
Information Retrieval and Extraction - Module 7
premSankar19
 
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
Tunnel Ventilation System in Kanpur Metro
220105053
 
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
Inventory management chapter in automation and robotics.
atisht0104
 
All chapters of Strength of materials.ppt
girmabiniyam1234
 

Class

  • 1. OOP OOP as a methodology that organizes a programinto a collection of interacting objects. A more technical definition asserts that OOP is a programming paradigm that incorporates the principles of encapsulation , inheritance , and polymorphism. ClassesandObjectsinJava ClassesandObjectsare basicconceptsof ObjectOrientedProgrammingwhichrevolvearoundthe real life entities. Class A classis a userdefinedblueprintorprototype fromwhichobjectsare created. Itrepresentsthe setof propertiesormethodsthatare commonto all objectsof one type.Ingeneral,classdeclarationscan include these components,inorder: Modifiers:A class can be publicor has defaultaccess(Refer this for details). Class name: The name shouldbeginwithaninitialletter(capitalizedbyconvention). Superclass(if any):The name of the class’sparent(superclass),if any,precededbythe keyword extends.A classcan onlyextend(subclass)one parent. Interfaces(if any): A comma-separatedlistof interfacesimplementedbythe class,if any,precededby the keywordimplements.A classcan implementmore thanone interface. Body:The classbody surroundedbybraces,{ }. Constructorsare usedforinitializingnew objects.Fieldsare variablesthatprovidesthe state of the class and itsobjects,andmethodsare usedto implementthe behaviorof the classanditsobjects. There are varioustypesof classesthatare usedinreal time applicationssuchas nested classes,anonymous classes,lambda expressions. Object It isa basicunitof ObjectOrientedProgramming andrepresentsthe real lifeentities. A typical Java program createsmanyobjects,whichasyouknow,interactby invokingmethods.Anobjectconsistsof : State :It is representedbyattributesof anobject.Italsoreflectsthe propertiesof anobject. Behavior :It is representedbymethodsof anobject.Italsoreflectsthe response of anobjectwith otherobjects. Identity :It givesa unique name toanobjectand enablesone objecttointeractwith otherobjects. Example of an object:dog
  • 2. Objectscorrespondtothingsfoundinthe real world.Forexample,agraphicsprogrammay have objects such as “circle”,“square”,“menu”.Anonline shoppingsystemmighthave objectssuchas“shopping cart”, “customer”,and “product”. Declaring Objects(Alsocalledinstantiating a class) Whenan objectof a classis created,the classissaidto be instantiated.All the instancesshare the attributesandthe behaviorof the class.But the valuesof those attributes,i.e.the state are unique for each object.A single classmayhave anynumberof instances. As we declare variableslike (type name;).Thisnotifiesthe compilerthatwe will use name toreferto data whose type istype.Witha primitive variable,thisdeclarationalsoreservesthe properamountof memoryforthe variable.Soforreference variable, type mustbe strictlyaconcrete classname.In general,we can’tcreate objectsof anabstract class or an interface. Dog tuffy; If we declare reference variable(tuffy) like this,itsvalue willbe undetermined(null) until anobjectis actuallycreatedandassignedtoit.Simplydeclaringa reference variable doesnotcreate anobject. Initializingan object The newoperatorinstantiatesaclassby allocatingmemoryforanew objectand returningareference to that memory.The newoperatoralsoinvokesthe class constructor.
  • 3. What are Methods? A methodisa setof code whichisreferredtoby name and can be called(invoked) atanypointina program simplybyutilizingthe method'sname. Thinkof a methodasa subprogramthat acts on data and oftenreturnsavalue. Each methodhas itsownname. Whenthat name is encounteredinaprogram, the executionof the program branchestothe bodyof that method. Whenthe methodisfinished,executionreturnstothe area of the programcode from whichitwas called,andthe programcontinuesonto the nextline of code. Good programmerswrite ina modularfashionwhichallowsforseveral programmerstowork independentlyonseparate conceptswhichcanbe assembledata laterdate to create the entire project. The use of methodswill be ourfirststepinthe directionof modularprogramming. Methodsare time savers,inthattheyallow forthe repetitionof sectionsof code withoutretypingthe code. In addition,methodscanbe savedandutilizedagainandagaininnewlydevelopedprograms. You are usingmethods whenyouuse System.out.print( ) andSystem.out.println( ). There are twobasictypesof methods: Built-in: Build-inmethodsare partof the compilerpackage,suchas System.out.println( ) and System.exit(0). User-defined:User-definedmethodsare createdbyyou,the programmer.These methods take-onnamesthatyouassignto themand performtasksthat youcreate. How to invoke (call) a method (methodinvocation): Whena methodisinvoked(called),arequestismade toperformsome action,suchas settingavalue, printingstatements,returningananswer,etc. The code to invoke the methodcontainsthe name of the methodtobe executedandanyneededdatathatthe receivingmethodrequires. The requireddatafor a methodare specified inthe method'sparameterlist. Considerthismethodthatwe have alreadybeenusingfromBreezy; intnumber= Console.readInt("Enteranumber"); //returnsavalue The methodname is"readInt"whichisdefinedinthe class"Console". Since the methodisdefinedin the class Console,the word Consolebecomesthe callingobject. Thisparticularmethodreturnsan integervalue whichisassignedtoanintegervariable named number.
  • 4. You invoke (call) amethodbywritingdownthe callingobjectfollowed byadot,thenthe name of the method,andfinallyasetof parenthesesthatmay(ormay not) have informationforthe method.A Java methodisa collectionof statementsthatare groupedtogethertoperformanoperation.Whenyoucall the System.out.println() method,forexample,the systemactuallyexecutesseveral statementsinorder to displayamessage onthe console. Nowyouwill learnhowtocreate yourownmethodswithorwithoutreturnvalues,invokeamethod withor withoutparameters,andapplymethodabstractioninthe programdesign. CreatingMethod Consideringthe followingexample toexplainthe syntax of amethod− Syntax publicstaticintmethodName(inta,intb) { // body } Here, publicstatic − modifier int − returntype methodName − name of the method a, b − formal parameters int a, int b − listof parameters Methoddefinitionconsistsof amethodheaderanda methodbody.The same isshowninthe following syntax − Syntax modifierreturnType nameOfMethod(ParameterList) { // methodbody } The syntax shownabove includes− modifier− It definesthe accesstype of the methodanditis optional touse. returnType − Methodmay returna value. nameOfMethod− Thisis the methodname.The methodsignature consistsof the methodname and the parameterlist. Parameter List − The listof parameters,itisthe type,order,and numberof parametersof a method. These are optional,methodmaycontainzeroparameters. methodbody − The methodbodydefineswhatthe methoddoeswiththe statements. Example Here is the source code of the above definedmethodcalled min().Thismethodtakestwoparameters num1 and num2 andreturnsthe maximumbetweenthe two− /** the snippetreturnsthe minimumbetweentwonumbers*/ publicstaticintminFunction(intn1,intn2) { intmin; if (n1 > n2) min= n2; else min= n1; returnmin; } MethodCalling
  • 5. For usinga method,itshouldbe called.There are twowaysinwhicha methodiscalledi.e.,method returnsa value or returningnothing (noreturnvalue). The processof methodcallingissimple.Whenaprograminvokesamethod,the programcontrol gets transferredtothe calledmethod.Thiscalledmethodthenreturnscontrol tothe callerintwoconditions, when− the returnstatementis executed. it reachesthe methodendingclosingbrace. The methodsreturningvoidisconsideredascall to a statement.Letsconsideranexample− System.out.println("Thisistutorialspoint.com!"); The methodreturningvalue canbe understoodbythe followingexample− intresult= sum(6,9); Followingisthe example todemonstrate how todefineamethodandhow to call it − Example Live Demo publicclassExampleMinNumber{ publicstaticvoidmain(String[] args) { inta = 11; intb = 6; intc = minFunction(a,b); System.out.println("MinimumValue=" + c); } /** returnsthe minimumof twonumbers*/ publicstaticintminFunction(intn1,intn2) { intmin; if (n1 > n2) min= n2; else min= n1; returnmin; } } Thiswill produce the followingresult− Output Minimumvalue =6 ThevoidKeyword The voidkeywordallowsustocreate methodswhichdonot returna value.Here,in the following example we're consideringavoidmethod methodRankPoints.Thismethodisavoidmethod,whichdoes not returnany value.Call toa voidmethodmustbe a statementi.e. methodRankPoints(255.7);.Itis a Java statementwhichendswitha semicolonasshowninthe followingexample. Example Live Demo publicclassExampleVoid{ publicstaticvoidmain(String[] args) {
  • 6. methodRankPoints(255.7); } publicstaticvoidmethodRankPoints(doublepoints){ if (points>= 202.5) { System.out.println("Rank:A1"); }else if (points>=122.4) { System.out.println("Rank:A2"); }else { System.out.println("Rank:A3"); } } } Thiswill produce the followingresult− Output Rank:A1 PassingParametersbyValue While workingundercallingprocess,argumentsistobe passed.These shouldbe inthe same orderas theirrespective parametersinthe methodspecification.Parameterscanbe passedbyvalue or by reference. PassingParametersbyValue meanscallingamethodwithaparameter.Throughthis,the argument value ispassedtothe parameter. Example The followingprogramshowsanexample of passingparameterbyvalue.The valuesof the arguments remainsthe same evenafterthe methodinvocation. Live Demo publicclassswappingExample{ publicstaticvoidmain(String[] args) { inta = 30; intb = 45; System.out.println("Before swapping,a= " + a + " and b = " + b); // Invoke the swapmethod swapFunction(a,b); System.out.println("n**Now,Before andAfterswappingvalueswillbe same here**:"); System.out.println("Afterswapping,a= " + a + " and b is" + b); } publicstaticvoidswapFunction(inta,intb) { System.out.println("Before swapping(Inside),a= " + a + " b = " + b); // Swapn1 withn2 intc = a; a = b; b = c; System.out.println("Afterswapping(Inside),a= " + a + " b = " + b);
  • 7. } } Thiswill produce the followingresult− Output Before swapping,a= 30 and b = 45 Before swapping(Inside),a= 30 b = 45 Afterswapping(Inside),a= 45 b = 30 **Now,Before andAfterswappingvalueswill be same here**: Afterswapping,a= 30 and b is 45 MethodOverloading Whena class has twoor more methodsbythe same name butdifferentparameters,itisknownas methodoverloading.Itisdifferentfromoverriding.Inoverriding,amethodhasthe same methodname, type,numberof parameters,etc. Let’sconsiderthe example discussedearlierforfindingminimumnumbersof integertype.If,let’ssay we want to findthe minimumnumberof double type.Thenthe conceptof overloadingwillbe introducedtocreate twoor more methodswiththe same name butdifferentparameters. The followingexample explainsthe same − Example Live Demo publicclassExampleOverloading{ publicstaticvoidmain(String[] args) { inta = 11; intb = 6; double c= 7.3; double d= 9.4; intresult1= minFunction(a,b); // same functionname withdifferentparameters double result2=minFunction(c,d); System.out.println("MinimumValue=" + result1); System.out.println("MinimumValue=" + result2); } // forinteger publicstaticintminFunction(intn1,intn2) { intmin; if (n1 > n2) min= n2; else min= n1; returnmin; } // fordouble
  • 8. publicstaticdouble minFunction(double n1,double n2) { double min; if (n1 > n2) min= n2; else min= n1; returnmin; } } Thiswill produce the followingresult− Output MinimumValue =6 MinimumValue =7.3 Overloadingmethodsmakesprogramreadable.Here,twomethodsare givenbythe same name but withdifferentparameters.The minimumnumberfromintegeranddouble typesisthe result. UsingCommand-LineArguments Sometimesyouwill wanttopasssome informationintoaprogramwhenyourun it.This isaccomplished by passingcommand-line argumentstomain( ). A command-lineargumentisthe informationthatdirectlyfollowsthe program'sname onthe command line whenitisexecuted.Toaccessthe command-line argumentsinside aJavaprogramis quite easy. Theyare storedas stringsinthe Stringarray passedto main( ). Example The followingprogramdisplaysall of the command-lineargumentsthatitiscalledwith− publicclassCommandLine { publicstaticvoidmain(Stringargs[]){ for(inti = 0; i<args.length;i++) { System.out.println("args["+i + "]: " + args[i]); } } } Try executingthisprogramasshownhere − $java CommandLine thisisacommandline 200 -100 Thiswill produce the followingresult− Output args[0]:this args[1]:is args[2]:a args[3]:command args[4]:line args[5]:200 args[6]:-100 Thethiskeyword this isa keywordinJavawhichisusedas a reference tothe objectof the currentclass,withinan instance methodora constructor.Using this youcan referthe membersof a classsuch as constructors, variables andmethods. Note − The keyword thisis usedonlywithininstancemethodsorconstructors
  • 9. In general,the keyword thisisusedto− Differentiate the instance variablesfromlocal variablesif theyhave same names,withinaconstructoror a method. classStudent{ intage; Student(intage) { this.age = age; } } Call one type of constructor (parametrizedconstructorordefault) fromotherinaclass.It isknownas explicitconstructorinvocation. classStudent{ intage Student() { this(20); } Student(intage) { this.age = age; } } Example Here is an example thatuses thiskeywordtoaccessthe membersof a class.Copyand paste the followingprogramina file withthe name, This_Example.java. Live Demo publicclassThis_Example { // Instance variable num intnum = 10; This_Example() { System.out.println("Thisisanexample programonkeywordthis"); } This_Example(intnum) { // Invokingthe defaultconstructor this(); // Assigningthe local variable numtothe instance variablenum this.num=num;
  • 10. } publicvoidgreet() { System.out.println("Hi Welcome toTutorialspoint"); } publicvoidprint() { // Local variable num intnum = 20; // Printingthe local variable System.out.println("valueof local variable numis:"+num); // Printingthe instance variable System.out.println("valueof instance variable numis:"+this.num); // Invokingthe greetmethodof aclass this.greet(); } publicstaticvoidmain(String[] args) { // Instantiatingthe class This_Example obj1=newThis_Example(); // Invokingthe printmethod obj1.print(); // Passinganewvalue tothe numvariable throughparametrizedconstructor This_Example obj2=newThis_Example(30); // Invokingthe printmethodagain obj2.print(); } } Thiswill produce the followingresult− Output Thisis an example programonkeywordthis value of local variable numis: 20 value of instance variable numis:10 Hi Welcome toTutorialspoint Thisis an example programonkeywordthis value of local variable numis: 20 value of instance variable numis:30 Hi Welcome toTutorialspoint VariableArguments(var-args) JDK 1.5 enablesyoutopassa variable numberof argumentsof the same type to a method.The parameterinthe methodisdeclaredasfollows− typeName...parameterName
  • 11. In the methoddeclaration,youspecifythe type followedbyanellipsis(...).Onlyone variable-length parametermaybe specifiedinamethod,andthisparametermust be the last parameter.Anyregular parametersmustprecede it. Example Live Demo publicclassVarargsDemo{ publicstaticvoidmain(Stringargs[]){ // Call methodwithvariable args printMax(34,3, 3, 2, 56.5); printMax(newdouble[]{1,2,3}); } publicstaticvoidprintMax( double...numbers) { if (numbers.length==0) { System.out.println("Noargumentpassed"); return; } double result =numbers[0]; for (inti = 1; i < numbers.length;i++) if (numbers[i] > result) result= numbers[i]; System.out.println("Themax value is"+ result); } } Thiswill produce the followingresult− Output The max value is56.5 The max value is3.0 Thefinalize()Method It ispossible todefineamethodthatwill be calledjustbefore anobject'sfinal destructionbythe garbage collector.Thismethodiscalled finalize( ),anditcan be usedto ensure thatan object terminates cleanly. For example,youmightuse finalize() tomake sure that an openfile ownedbythatobjectisclosed. To add a finalizertoaclass, yousimplydefine the finalize() method.The Javaruntime callsthatmethod wheneveritisaboutto recycle an objectof that class. Inside the finalize() method,youwillspecifythose actionsthatmustbe performedbefore anobjectis destroyed. The finalize( ) methodhasthisgeneral form− protectedvoidfinalize( ) { // finalizationcode here } Here,the keywordprotectedisaspecifierthatpreventsaccesstofinalize() bycode definedoutside its class.
  • 12. FINAL VARIABLES A final variable is a variable that is assigned a permanent value. A final variable may be assigned a value justonce in any program, and once assigned, the value cannot be altered. Its value is, well, “final.” In Example 3.5, the value 3.14159 is thevalue 3.14159 is assigned to PI as partof the declaration. It is a good practice to initialize a final variable when it is declared. By convention, names of final variables arecomprised of uppercaseletters with underscores separating the“words” of a name. For example, PI, TAX_RATE and FIDDLE_DEE_DEE adhere to this practice area PI *radius*radius, Thismeansthat youcannot knowwhenor evenif finalize( ) will be executed.Forexample,if your program endsbefore garbage collectionoccurs,finalize( ) willnotexecute. String Concatenation . For example,the statement System.out.println("Frankenstein" "meets" "Dracula"); effectsthe concatenationof three strings:"Frankenstein"," meets",and "Dracula". Concatenation is the process of joining, connecting, or linking Strings together. What is Abstraction Abstractionisa processof hidingthe implementationdetailsfromthe user.Оnlythe functionalitywill be providedtothe user. In Java,abstractionisachievedusingabstractclassesandinterfaces.We have a more detailedexplanationonJavaInterfaces,if youneedmore infoaboutInterfaces pleasereadthis tutorial first. Abstractionisone of the fourmajorconceptsbehind object-orientedprogramming(OOP).OOP questionsare verycommoninjobinterviews,soyoumayexpectquestionsaboutabstractiononyour nextJavajob interview. AbstractClassin Java Abstractclass inJava issimilartointerface exceptthatitcan containdefaultmethodimplementation. An abstractclass can have an abstract methodwithoutbodyanditcan have methodswith implementationalso. abstract keywordisusedtocreate an abstract class and method.Abstractclassinjavacan’t be instantiated.Anabstractclassismostlyusedtoprovide abase for subclassestoextendandimplement the abstract methodsandoverride oruse the implementedmethodsinabstractclass.
  • 13. package com.journaldev.design; //abstractclass publicabstractclass Person{ private Stringname; private Stringgender; publicPerson(Stringnm,Stringgen){ this.name=nm; this.gender=gen; } //abstractmethod publicabstractvoidwork(); @Override publicStringtoString(){ return"Name="+this.name+"::Gender="+this.gender; } publicvoidchangeName(StringnewName) { this.name =newName; } } Notice thatwork() isan abstract methodand ithas no-body.Here isa concrete classexample extending an abstract classin java. package com.journaldev.design; publicclassEmployee extendsPerson{ private intempId; publicEmployee(Stringnm,Stringgen,intid) { super(nm,gen); this.empId=id; } @Override publicvoidwork() { if(empId==0){ System.out.println("Notworking"); }else{ System.out.println("Workingasemployee!!");
  • 14. } } publicstaticvoidmain(Stringargs[]){ //codingintermsof abstract classes Personstudent=newEmployee("Dove","Female",0); Personemployee =newEmployee("Pankaj","Male",123); student.work(); employee.work(); //usingmethodimplementedinabstractclass - inheritance employee.changeName("Pankaj Kumar"); System.out.println(employee.toString()); } } Note that subclassEmployeeinheritsthe propertiesandmethodsof superclassPerson usinginheritance in java. Abstractclass inJava ImportantPoints abstract keywordisusedto create an abstract classin java. Abstractclass injava can’t be instantiated. We can use abstract keywordtocreate an abstract method,anabstract methoddoesn’thave body. If a classhave abstract methods,thenthe classshouldalsobe abstractusingabstract keyword,else it will notcompile. It’snot necessaryforan abstract classto have abstract method.We can mark a class as abstract evenif it doesn’tdeclare anyabstractmethods. If abstract class doesn’thave anymethodimplementation,itsbettertouse interface because java doesn’tsupportmultiple classinheritance. The subclassof abstract classinjava mustimplementall the abstractmethodsunlessthe subclassisalso an abstract class. All the methodsinaninterface are implicitlyabstractunlessthe interface methodsare staticor default. Staticmethodsanddefaultmethodsininterfacesare addedin Java 8, formore detailsread Java 8 interface changes. Java Abstractclass can implementinterfaceswithoutevenprovidingthe implementationof interface methods. Java Abstractclass isusedto provide commonmethodimplementationtoall the subclassesorto provide defaultimplementation. We can run abstract classin javalike anyotherclassif it has main() method. Why we needanabstract class? Letssay we have a class Animal that hasa method sound() and the subclasses(see inheritance) of it like Dog, Lion, Horse, Cat etc. Since the animal sounddiffersfromone animal toanother,there isno pointto implementthismethodinparentclass. Thisisbecause everychildclassmustoverride this methodtogive itsownimplementationdetails,like Lionclasswill say“Roar” in thismethod and Dog classwill say“Woof”.
  • 15. So whenwe knowthatall the animal childclasseswill andshouldoverride thismethod,thenthere isno pointto implementthismethodinparentclass.Thus,makingthismethodabstractwouldbe the good choice as by makingthismethodabstractwe force all the sub classestoimplementthismethod( otherwise youwillgetcompilationerror),alsowe neednottogive anyimplementationtothismethod inparentclass. Since the Animal classhas an abstract method,youmustneedtodeclare thisclassabstract. Noweach animal musthave a sound,bymakingthismethodabstractwe made it compulsorytothe childclassto give implementationdetailstothismethod.Thiswaywe ensuresthateveryanimal hasa sound. Abstractclass Example //abstract parent class abstract class Animal{ //abstract method public abstract void sound(); } //Dog class extends Animal class public class Dog extends Animal{ public void sound(){ System.out.println("Woof"); } public static void main(String args[]){ Animal obj = new Dog(); obj.sound(); } } Output: Woof Hence for suchkindof scenarioswe generallydeclarethe classasabstract and later concrete classes extendthese classesandoverride the methodsaccordinglyandcanhave theirownmethodsas well. Abstractclass declaration An abstractclass outlinesthe methodsbutnotnecessarilyimplementsall the methods. //Declaration using abstract keyword abstract class A{ //This is abstract method abstract void myMethod(); //This is concrete method with body void anotherMethod(){ //Does something } }
  • 16. What is the difference between up-casting and down-casting with respect to class variable What isthe difference betweenup-castinganddown-castingwithrespecttoclassvariable? For example inthe followingprogramclassAnimal containsonlyone methodbutDogclasscontainstwo methods,thenhowwe castthe Dog variable tothe Animal Variable. If casting isdone thenhowcan we call the Dog's anothermethodwithAnimal'svariable. classAnimal { publicvoidcallme() { System.out.println("Incallme of Animal"); } } classDog extends Animal { publicvoidcallme() { System.out.println("Incallme of Dog"); } publicvoidcallme2() { System.out.println("Incallme2of Dog"); } } publicclassUseAnimlas { publicstaticvoidmain(String[] args) { Dog d = new Dog(); Animal a= (Animal)d; d.callme(); a.callme(); ((Dog) a).callme2(); } } Upcastingis castingto a supertype,while downcastingiscastingtoa subtype.Upcastingisalways allowed,butdowncasting involvesatype checkand can throw a ClassCastException. In yourcase,a cast froma Dog to an Animal isanupcast, because aDog is-aAnimal.Ingeneral,youcan upcast wheneverthere isanis-arelationshipbetweentwoclasses. Downcastingwouldbe somethinglikethis: Animal animal =new Dog(); Dog castedDog= (Dog) animal;
  • 17. Basicallywhatyou're doingistellingthe compilerthatyouknow whatthe runtime type of the objectreally is.The compilerwillallow the conversion,butwill still inserta runtime sanitycheckto make sure that the conversionmakessense.Inthiscase,the cast ispossible because atruntime animalis actuallya Dog eventhoughthe statictype of animal isAnimal. However,if youwere todo this: Animal animal =new Animal(); Dog notADog= (Dog) animal; You'd geta ClassCastException.The reasonwhyisbecause animal'sruntimetype is Animal,andsowhen youtell the runtime toperformthe cast it seesthat animal isn'treallyaDog and so throws a ClassCastException. To call a superclass'smethodyoucando super.method() orbyperformingthe upcast. To call a subclass'smethodyouhave todo a downcast.Asshownabove,younormallyrisk a ClassCastException bydoingthis;however,youcanuse the instanceof operatortocheck the runtime type of the objectbefore performingthe cast,whichallowsyoutoprevent ClassCastExceptions: Animal animal =getAnimal();//Maybe a Dog?Maybe a Cat? Maybe an Animal? if (animal instanceof Dog) { // Guaranteed tosucceed, barringclassloadershenanigans Dog castedDog= (Dog) animal; } Down-castingandup-castingwasasfollows:
  • 18. Upcasting:Whenwe want to cast a Sub classto Superclass,we use Upcasting(orwidening).Ithappens automatically,noneedtodoanything explicitly. Downcasting :When we wantto cast a Superclassto Subclass,we use Downcasting(ornarrowing), and Downcastingisnotdirectlypossible inJava,explicitlywe have todo. Dog d = new Dog(); Animal a = (Animal) d; //Explicitly you have done upcasting. Actually no need, we can directly type cast like Animal a = d; compiler now treat Dog as Animal but still it is Dog even after upcasting d.callme(); a.callme(); // It calls Dog's method even though we use Animal reference. ((Dog) a).callme2(); // Downcasting: Compiler does know Animal it is, In order to use Dog methods, we have to do typecast explicitly. // Internally if it is not a Dog object it throws ClassCastException Upcastingand downcastingare importantpartof Java,whichallow usto buildcomplicatedprograms usingsimple syntax,andgivesusgreatadvantages,like Polymorphismorgroupingdifferent objects. Javapermitsan object of a subclasstype to be treated asan object of any superclass type. This iscalled upcasting.Upcastingisdoneautomatically, whiledowncasting mustbemanuallydone by the programmer, andi'm goingto give mybestto explainwhyisthatso. Upcastingand downcastingare NOTlike castingprimitivesfromone toother,andi believe that'swhat causesa lot of confusion,whenprogrammerstartstolearncastingobjects. Polymorphism:All methodsinjava are virtual by default.That means that any methodcan be overridden whenused in inheritance, unlessthat method isdeclared as final or static. You can see the example belowhow getType();worksaccordingtothe object(Dog,Pet,Police Dog) type. Assume youhave three dogs Dog - Thisis the superClass. PetDog - PetDog extendsDog. Police Dog- Police DogextendsPetDog. publicclassDog{ publicStringgetType () { System.out.println("NormalDog"); return"NormalDog"; } } /** * PetDog has an extramethoddogName() */ publicclassPetDogextends Dog{ publicStringgetType () { System.out.println("PetDog"); return"PetDog"; } publicStringdogName () { System.out.println("Idon'thave Name !!"); return"NOName";
  • 19. } } /** * Police Doghas an extramethodsecretId() */ publicclassPoliceDogextends PetDog{ publicStringsecretId() { System.out.println("ID"); return"ID"; } publicStringgetType () { System.out.println("IamaPolice Dog"); return"Police Dog"; } } Polymorphism:All methodsinjavaare virtual bydefault.Thatmeansthat anymethodcan be overriddenwhenusedininheritance,unlessthatmethodisdeclaredasfinal orstatic.(Explanation BelongstoVirtual TablesConcept) public static void main (String[] args) { /** * Creating the different objects with super class Reference */ Dog obj1 = new Dog(); ` /** * Object of Pet Dog is created with Dog Reference since * Upcasting is done automatically for us we don't have to worry about it * */ Dog obj2 = new PetDog(); ` /** * Object of Police Dog is created with Dog Reference since * Upcasting is done automatically for us we don't have to worry * about it here even though we are extending PoliceDog with PetDog * since PetDog is extending Dog Java automatically upcast for us */ Dog obj3 = new PoliceDog(); } obj1.getType(); PrintsNormal Dog
  • 20. obj2.getType(); PrintsPet Dog obj3.getType(); PrintsPolice Dog Downcasting need to be done by the programmer manually Whenyoutry to invoke the secretID(); methodon obj3 whichis PoliceDog object but referenced to Dog whichisa superclassinthe hierarchyitthrowserrorsince obj3 don't have access to secretId() method.In order to invoke that method you need to Downcast that obj3 manually toPoliceDog ( (PoliceDog)obj3).secretID(); whichprintsID In the similarwaytoinvoke the dogName();methodin PetDog classyou needto downcastobj2 to PetDog since obj2isreferencedto Dog and don't have access to dogName(); method ( (PetDog)obj2).dogName(); Why isthat so,that upcastingis automatical,butdowncastingmustbe manual?Well,yousee,upcasting can neverfail.Butif youhave a groupof differentDogsandwantto downcastthemall to a to their types,thenthere'sachance,that some of these Dogsare actuallyof differenttypes i.e., PetDog,PoliceDog, and processfails,bythrowing ClassCastException. Thisis the reasonyouneedto downcast your objects manually if you have referencedyourobjects to the superclass type.