0% found this document useful (0 votes)
51 views18 pages

Ctod Week 6

Uploaded by

rutwika06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views18 pages

Ctod Week 6

Uploaded by

rutwika06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Week-6

Lab Session:

Date of the Session:6 /02/24 Time of the Session: 24


930 03NS to 42t
Prerequisites:
" Inheritance
Method Overloading, and Method Overriding
Pre-Lab:
1. What is the purpose of inheritance?
By uing inheitance, 0e an achieve ce reDability arnd
reuce Oredundarg
2. Can we override the static method in Java?
No,e caumot oeide the
statie method in Java. Because

3. What is
method signature? What are the
Method ciarature consicist methodthings it consists of?
Paramete list indicates te name and paranetey li
panameteve. ronametes hd det o
4. What is
method
Tot ox rnore overloading?
metbocts hNin
aiteven metho ciqna 6ame name ht ath

5. What is
turetithin the come class.
method overriding?
to povid a teatwe Jiva fhat alloo a sabcag
in
alrendy prcvided bynmpeme nfaia fon a metiod that is
ie super clas
In-lab:
1. Write the following code in your editor below:
A class named Arithmetic with a method named add that
as parameters and takes integeIo
returns an integer denoting their
A class named Adder that
LINK: bit.ly/CTOOD-W6P02
inherits from asuDer classsum.
named Arithmeu
Class Diagram: kla tockage
lass Name Aithmetic Ader

Solrtín >cias

Meod. 4 main Cas inai):vod Method

Programn: class titometicf


add Cinta,int

closs Adder etends Aithmeic

clacs Solation f
pu~ie statie oid main (shing t) ag
feolie
Aldev a-neo Adder()',

Syem out pintn y uperchus is:agtclan(qet apeoclau().


qet Name())
System out pint/n (a-adt (to 32) 4" ta add (lo,3)+"+a ad(to,1o)
+ "\1n'))
COutpt
hy sipercas is :fnthm efic
42 3 20
2. Write a java progranm to create a class name
(with same method name with different 2rmument) called kumber with 2 menou
In main methods call the
methods based on the argument and observe the output
Class Diagram:
lu
>cautNone
Numoer
> Att ibutes

+add Cint ,int) int


> Method.

Program: ackaqe klu) mport java-utt Scavne


ousle dase Num be
puire retun *y)
pudic int add mt a,int b, int
reton atbtc

padie totie void main (Sringt) arg


Saone se neo Scanne (Sptem in
Numbey n neo Nernber ))

oitn (o add e2,3);


tomcet-
?
4
3. Create two classes Bike and Splendor.
Splendor class extends Bike clasSS
and overrides its run ) method. In main method
and observe the output call the overridemethods
Class Diagram: klu Poekage
Clcs Nanc Bike Splendov Bike Demo

+runey:void

Program:
pablie cay Bikef
publie void Yun() coheeis "):
ten("A bike has too
Septem out pin

pubic clas Splen eterds Bikef


public void runc
n(Some ikes have three heels",
System out pint
Turle olas BikeDemo
public tatic vcid ain( nng o ags
plerdor lento(

wheels
ikes ha ve tvep
Post lab:

1. When a method in a subelass overrides a method in super class, it in still


possible to call the overridden method using super keyword. If you write
super.func)to callthe function func), it will call the method that was deei
the super class. You are given a partially completed code in the editor. Modify
thecode so that the code prints the following text: "Hello Iam a notorcycle, Iatm
acyele with an engine. My ancestor is a cycle who is a vehicle with pedal
Link: https://bitly/3Lpirdk

Class Diagram: klu ckage


Cycie tAclter Cycle Solutin

+detrem(s:Ghing
Metinod,
jtdetine-we):gi
Program:
.mpert joa util
alas Picyeiei
hing defne-merg
Yetuan a vhicle toith (edas"
elas Motolycle exterdi bcydef
shing defhe -meOf
retn o
ycle with an eqme";

Gynu print n("ele T amn


4 define meo):
Motor Cyclel))

a metr cyce, I am a cyete with an enan:


yaret is acycle oho isa veide coih pedaly
2.Write a java program to demonstrate method overloading to perform additio
of two variables with different parameter types (int. double, String, and int
array).
Class Diagram:
4bckage
Weekb >coceame

>Attibetes
4addldoudrsehe
4nd(shing) stng Molhodc
todd (int():in

Program:
klaj
package
pudie dous toeek&
pubtic atetie docaale add (douse a, doabe bs
vetorn athy
3putslie okate stinq add
Qdd (sting'
(ting t, hin oX
rethoin St
3 publie ctate int acdd Cint( ) f

for (int i-o;icalevgth ; it


Yeton 3m}

ihie trtie vo td maim (Sing rqot


Seystem oat pinn (odd (s,l6);
Skill Session:
1. Create GeometricShape Class with attributes borderColor (String). nied
(Boolean type). This is inherited by Rectangle Class with length and width as
attributes. Add mutators, accessors and toString 0 methods, use appropriate
access specifier (protected). (Simple Inheritance)
Class Diagram:

Georehiear Cetin'e
boie Color. iergth dou ble

toci

Program: ockaae klui


pusik Clas Geometic Shaet
pateeted Shing bosderolor;
potecled boclan filledi
puble Geometic hape (aine tonderola, bolear flab
this.bor dee Color= bodeolors
thisflled =tled) histodes colo -borderCola)
3poleeted ching qet eader lort <patectecl voidctfillas (tolea-iledg
te ton BosderCo lor ; this tilled =4lled,
prote ed boolen icfilled(>f
reton flla
yetun "Rudercdu: "+hoderColort Flel ftles
tctet ted dace cod
heRoctaje (ty heteoer ko kti lled,cbute
uer(hIÉbler.fItd; length, doiie
islengtt. lengt
this coh codh
desd dausle getlongthe f
eten lenty
iedet doable qeticthot
rekan oidh)
oieeked voe atleyth (do ble Cengtiy
4his lengthelengthy
potecled void yet(Didth (doble oidthf
this i th oidh

tekon "eeckangle "s:lerg "w="coidth"\n


eble class Geomeic Shape De mal
pabiic tatie void main tstinq í] argsf
Sremetne ghape9 h Geometicshape (Rec taey
spi en d trintn epmetrte npehals?
Cectae l ve Rectavgle glue' fale, 50,30)
spien.ot prinl nliRectange Dedals: ay}

Pecargte etests;
Rec tagr
194
3. Create a class Area with three static overloading methods calculateArea
(double radius) to find area of a cicle,calculateArea (double 1,double b) to find
area of a rectangle and calculateArea(int s) to find area of a square. Access them
from the main) of same class. (Use Command Line Arguments)
Class Diagram: klu tckag
Area ClasG Name

Atioutes
+caltea Cdouble). doude
+al Aee (Aoute,doubley : doube Metigde.
4 calea Cint: int
main (arStingr):vo id
klu )
Program:
packag
prublie cass tren
pubtic satic deeble cal Are(double Raciuss
te tuon Mceth PI Meth
PooRodies,2)';
Spuiotie stahie doute al treu (daubielegit deusle coide) £
reten legtht conth
3 pebic state nt caltrea ((int f
Yetem ts
puslic datic vod mainlhingarsk
if Ceg levgih-:01
Systemutpiantho (noCommand fine thrmnli;
Tetuom
int S
Siplemcut pint fn("ca ¢ Square is'+ ol Ara(),
ele it (o length
dede Radies eCoube pae Double (asLo))
s:cdArea
Syle out pintlm 'Ae of+ drcle
deuble lergth =Doubse petoue(arost (eadiu)
double aidth Dauble poseDoube (agA cn
Sytmtat-pint tofAyea tReckange ts:+ cadlhea (lenyth, tdrh )
3glem out inn("No cominard lire Aqument"'y

Ctpet
inpt3

108
4. Create GeometricShape Class with attributes borderColor (String), filled
(Boolean type). This is inherited by Rectangle Class with length and width as
attributes.The Rectangle class is further inherited by Cuboid class with height
field as its instance variable. Add mutators, accessors and toString () methods.
Use super keyword. (Multilevel Inheritance). Enhance all classes with no
parameterized and parameterized constructor and Chain the constructors using
super keyword.
Class Diagram:

GeomeneShae Rectangle Cittd22 Rectarale Dero


b:Sthhra lerin: clou de

+sti'ecooat

Program: klus
puble cs, Geometnc Shapei thisbe Bondes Colo

pote cted rometnapeoi peaue


thi bc= Black!)
uo\d set Filled (konleun fillety
thiis, filled filad
thie flles -false;
puslic Geometic Shape( tnng ho ida Color, is aleon fitle0f
this bc - borcier ola;
this illed file;

i publie bcolegn ictillatc


re tontiled,
er dou hle oitih;
Seckayect he (oth(ota ilted, tenth odt t
this herght\
this legtne
thi cth o 0: d
dochle
qeittetgoht
tAejgt cdoe hes

doude ength dade odiiy


Sues (hde Colo filied), putbre eting totingof
rckon supe tasbngtt ntelgnt:"4heig*t;
thetslevgth -(engti) impat janutisann eys
ev
{this coithotdf ih puc clas
Reergle em
eahe vojd Ymain (Sing a )
lengi Nanmer
Scanneye neo Sa herCSte-(n;
I pebfic doade qet withey Gemee chape shape1 =neohetmehte Sap (Pe, ag
4et coidn
Syden aut pntla(Gconefic Shqe cbj Creded;shi
pubiekoelean getlengh teêitieietange reneo fecti( B flae,so,so,
Syero-oud pvin lenyeoj ciealed:')
this e gth-kicuhoid 2) c=neo Caaeuá(Rec
re tun fuey Gen-oud pin 2) Green", teto6O VO)
Gsemout ("Cabed 2 cbj creale:"Ac,
doute neolengh neobíeo)
4 Setlenth(neol eytay
=e.next Doubcly
ths-wictity) rsHeignt (he hetghe

tet Boxte Cslo: Rel


Ree larsle chj crelks
Bler ColoY: u
sWnte a java program to Create Monster as super class and add parameterized
oonstructor in the class. To create three subclasses mentioned in below diagram
whch overrdes the attack 0 method and returns String. Display the attacking
methads of each monster from main ) method of Demo class
Class Diagram:

NorsY Monste Demo

Program:
fnckaqe hle;

priuateving rvre)
I.
tname(o

reton
puite chk Mtxster2 ( ing nane%

atacho
rekon KiH Monster 2"1petName(+' is atetina;
puble dau childMter 3 etends Mosterj
puble child Noesler3 (Sing t mey
Supertame;
pudic Shiì nq atak (){
vetum child Hyester s is'tqetNane)+ "'atacks
pablic dauy MbasterDeof
pulslic staie void nan(sting) ara
M es ter m ne

3lem out pi Cn- attacke


2hild MeAler MInew Child Morler(CVeuhan0;
ehid Mo,tes m hew Chld
MasferSethdy
hild Mbaster m ne child Moste Tray
Gystempet pirln (nt- attek s
"mten cd println CgaftackO

Rrnt tita.ter UHhin is atackinq


hdMoslrrl Voshan is attacking
atackr"9
112
6Implement the following leetcode program using method overloading. You are
en an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and
shoosing a difterent day in the future to sell that stock. Return the maximum
nit vou can achieve from this transaction. If you
retum 0. cannot achieve any profit,
LNK: https://bit.ly/CTOOD W3SKILL2
Class Diagram:lcck6t
Pockone
SolutieY

imorBoit (n int )Metod


rrain (ors:din):void
Program:
pachaqe leek6;
ublic cacs Soleti en
pubtic int maa Po it (int ( pic ey f
HAK VAL UE,

int pist =0)


for (int ir0; ic pmc es tength; tt+{
it(rices(3esH
|st -icesn

it Cop< pie)i
Tetun opi

Tnput:
tce:lt, s,3.6,4)

(For
Evaluator's use only)
Comment of the Evaluator (if Any)
Evaluator's Observation
4 2outof
Marks Secured:

Full Name of the Evaluatort


B.i
Signatureohe Evaluator Dhie

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy