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
PPTX
Java method
PPTX
Object oriented programming in python
PDF
Object Oriented Programming Lab Manual
DOC
Faqs in java
PDF
Implementation
PDF
ASE02.ppt
ODP
Method Handles in Java
Architecture of a morphological malware detector
Java method
Object oriented programming in python
Object Oriented Programming Lab Manual
Faqs in java
Implementation
ASE02.ppt
Method Handles in Java

What's hot (18)

PDF
Oop basic concepts
DOCX
core java syllabus
PDF
maXbox Starter 31 Closures
PDF
Core java interview faq
PPT
Chap03
PPT
Chap03
PDF
Object-oriented Programming in Python
PPTX
Java Method, Static Block
DOCX
Intervies
DOCX
Mcs 024 assignment solution (2020-21)
PPT
Java căn bản - Chapter7
PPTX
Java interview questions 1
PDF
A Logic Meta-Programming Foundation for Example-Driven Pattern Detection in O...
KEY
What's New In Python 2.4
DOC
Questions of java
PPT
Oo Design And Patterns
DOC
[PDF]
KEY
What's New In Python 2.5
Oop basic concepts
core java syllabus
maXbox Starter 31 Closures
Core java interview faq
Chap03
Chap03
Object-oriented Programming in Python
Java Method, Static Block
Intervies
Mcs 024 assignment solution (2020-21)
Java căn bản - Chapter7
Java interview questions 1
A Logic Meta-Programming Foundation for Example-Driven Pattern Detection in O...
What's New In Python 2.4
Questions of java
Oo Design And Patterns
[PDF]
What's New In Python 2.5
Ad

Similar to Class (20)

PDF
Web Technology-Method .pdf
PPTX
OOPJ.pptx
PPTX
UNIT1-JAVA.pptx
PPTX
1. Methods presentation which can easily help you understand java methods.pptx
PPTX
Application package
PPT
Unit 1 Java
PDF
JAVA-PPT'S.pdf
PDF
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
PPTX
Unit 1
PPTX
JAVA-PPT'S-complete-chrome.pptx
PPTX
JAVA-PPT'S.pptx
PPTX
Chapter-3 Scoping.pptx
PPTX
Polymorphism presentation in java
PPTX
c & c++ logic building concepts practice.pptx
PPTX
Learn C# Programming - Encapsulation & Methods
DOCX
Java interview questions
DOCX
Java notes
PDF
polymorphismpresentation-160825122725.pdf
DOCX
I assignmnt(oops)
PDF
Supporting software documentation with source code summarization
Web Technology-Method .pdf
OOPJ.pptx
UNIT1-JAVA.pptx
1. Methods presentation which can easily help you understand java methods.pptx
Application package
Unit 1 Java
JAVA-PPT'S.pdf
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Unit 1
JAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S.pptx
Chapter-3 Scoping.pptx
Polymorphism presentation in java
c & c++ logic building concepts practice.pptx
Learn C# Programming - Encapsulation & Methods
Java interview questions
Java notes
polymorphismpresentation-160825122725.pdf
I assignmnt(oops)
Supporting software documentation with source code summarization
Ad

Recently uploaded (20)

PDF
UEFA_Carbon_Footprint_Calculator_Methology_2.0.pdf
PDF
Lesson 3 .pdf
PPTX
Solar energy pdf of gitam songa hemant k
PDF
Computer System Architecture 3rd Edition-M Morris Mano.pdf
PPT
Programmable Logic Controller PLC and Industrial Automation
PDF
Micro 4 New.ppt.pdf a servay of cells and microorganism
PDF
MACCAFERRY GUIA GAVIONES TERRAPLENES EN ESPAÑOL
PPTX
Micro1New.ppt.pptx the main themes if micro
PDF
Mechanics of materials week 2 rajeshwari
DOCX
ENVIRONMENTAL PROTECTION AND MANAGEMENT (18CVL756)
PDF
20250617 - IR - Global Guide for HR - 51 pages.pdf
PPTX
Wireless sensor networks (WSN) SRM unit 2
PDF
Project_Mgmt_Institute_-Marc Marc Marc .pdf
PPTX
Micro1New.ppt.pptx the mai themes of micfrobiology
PPTX
MAD Unit - 3 User Interface and Data Management (Diploma IT)
PPTX
WN UNIT-II CH4_MKaruna_BapatlaEngineeringCollege.pptx
PDF
VTU IOT LAB MANUAL (BCS701) Computer science and Engineering
PDF
Cryptography and Network Security-Module-I.pdf
PDF
Research on ultrasonic sensor for TTU.pdf
PDF
Unit I -OPERATING SYSTEMS_SRM_KATTANKULATHUR.pptx.pdf
UEFA_Carbon_Footprint_Calculator_Methology_2.0.pdf
Lesson 3 .pdf
Solar energy pdf of gitam songa hemant k
Computer System Architecture 3rd Edition-M Morris Mano.pdf
Programmable Logic Controller PLC and Industrial Automation
Micro 4 New.ppt.pdf a servay of cells and microorganism
MACCAFERRY GUIA GAVIONES TERRAPLENES EN ESPAÑOL
Micro1New.ppt.pptx the main themes if micro
Mechanics of materials week 2 rajeshwari
ENVIRONMENTAL PROTECTION AND MANAGEMENT (18CVL756)
20250617 - IR - Global Guide for HR - 51 pages.pdf
Wireless sensor networks (WSN) SRM unit 2
Project_Mgmt_Institute_-Marc Marc Marc .pdf
Micro1New.ppt.pptx the mai themes of micfrobiology
MAD Unit - 3 User Interface and Data Management (Diploma IT)
WN UNIT-II CH4_MKaruna_BapatlaEngineeringCollege.pptx
VTU IOT LAB MANUAL (BCS701) Computer science and Engineering
Cryptography and Network Security-Module-I.pdf
Research on ultrasonic sensor for TTU.pdf
Unit I -OPERATING SYSTEMS_SRM_KATTANKULATHUR.pptx.pdf

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.