SlideShare a Scribd company logo
1 of 19
Classes, Methods and
                      Inheritance
           SCJP / OCJP objectives : 1.1, 1.2, 1.3,
                         1.4, 5.5




                                                 By,
www.JAVA9S.com                            Srinivas Reddy.S
Declaring Classes
   Syntax:
   package com.java9s.ocjp;
   import com.sun.sample;
   class Car{
    int speed;  State
    void move(){  behaviour
    //code related to move
    }
   }
   Save the file with Car.java.
    If there are multiple classes in a file, the file name should
      be the name of the class with public access modifier.

www.JAVA9S.com
Declaring classes - Rules
   • The package statement should be the first
     statement in a file if the class belongs to a
     package.
   • Import statements comes next to package
     statement.
   • The order packageimportclass should be
     maintained.
   • Comments can come anywhere in the java file.
   • A java file can have any number of non public
     class files


www.JAVA9S.com
Declaring classes - Rules
   • package and import statements declared in a
     file apply to all the classes defined in the file.
   • A separate .class file will be generated for
     each class defined in the java file.
   • Any name can be given to a file when there is
     no public class declared in it.




www.JAVA9S.com
Creating Objects

    Car c = new Car();

                        Instantiation
      Declaration


  C is the reference which holds the           Car
                                            Speed=50
  memory address of the Car object
                                        C
www.JAVA9S.com
Creating Objects
   Car a = new Car();   a
   Car b = new Car();   b
   Car c = new Car();   c
   Car d = new Car();   d

   Car e = d;           e

                            d.speed =60;
                            System.out.println(e.speed) ;-> 60

www.JAVA9S.com
Methods
   • Methods are members of a class.
   • Methods have the behavior of an object.
   • Methods can be declared with or without
     arguments.
   • Two variants for a method:
       – Methods that return something
       – Methods that don’t return anything - void



www.JAVA9S.com
Methods – Return type
   Syntax:
   type methodName(arguments){
   //code that decides the methods
   return x;
   }
   E.g.,
   int addition(int a, int b){
      int c = a+b;
   return c;
   }


www.JAVA9S.com
Methods – void type
    Syntax:
   void methodName(arguments){
   //Method code.. No need to return anything.
   }
   E.g.,
   void saveToFile(String message){
   //Code related to saving message to file..
   }

www.JAVA9S.com
Method – without argument
   Method with No arguments and with a return type:
   Date getCurrentDate(){
   return Calender.get(Calender.DAY_OF_MONTH);
   }

   Method with no argument and no return type
   void printCurrentDate(){
   System.out.println(Calendar.get(Calender.DAY_OF_MONTH));
   }



www.JAVA9S.com
Inheritance
   • Inheritance is a way to reuse code from
     already existing types or objects.
   • Inheritance is implemented between two
     classes using extends keyword.
   • When a class extends another class,
     extending class is called subclass and
     extended class is super class.


www.JAVA9S.com
Inheritance
   class Car{
       void move(){                        •Car is super class
      System.out.println(“Moves”);         •Ford is subclass.
      }
   }
   class Ford extends Car{
                                         Ford f = new Ford();
                                         f.moveFast();
     void moveFast(){
                                         f.move();
     System.out.println(“Moves Fast”);
      }
   }

www.JAVA9S.com
Inheritance
   • With inheritance, all the members of super
     class are available to the subclass objects.
   • When a class extends another class, it has an
     IS-A relation with its super class.
   • instanceof keyword can be used to confirm
     IS-A relationship.




www.JAVA9S.com
Right or Wrong??
   class Car{ }
   class Ford extends Car{ }
   class BMW extends Car{ }

                           f instanceOf Car
    Ford f = new Ford();   f instanceOf BMW
    BMW b = new BMW();
    Car c = new Car();
                           b instanceOf Ford
                           b instanceOf Car
                           c instanceOf Ford
www.JAVA9S.com
super and this keywords
   • super is used to access the super class
     members.
   • this is used to access the currently executing
     objects members.




www.JAVA9S.com
super - example
   class Car{
     int speed;
   }
   class Ford extends Car{
      int speed;
      void move(){
      System.out.println(“Moving with car
      speed:”+super.speed)
      }
   }

www.JAVA9S.com
this - example
   class Ford{
      int price;                       int price;
                                       setFordPrice(int price){
      setFordPrice(int price){         this.price = price;
      this.price = price;              }

      }
   }                               a
   Ford a = new Ford();
   a.setFordPrice(3000);
   ‘this’ is not mandatory. But if you have local variables
      declared inside a method, to avoid confusion, this can
      be used to refer to members of the object.

www.JAVA9S.com
HAS-A relationship
   class Student{
     Pen p = new Pen();
   }
   class Pen{
   }
   Student HAS-A pen.
                     HAS – A relationship helps to reduce
                     the complexity of the classes by the
                     composition of the other classes.
www.JAVA9S.com
Thank you
   Follow me on to get more updates on latest video posts
   Subscribe on

   http://www.youtube.com/user/java9s
   Twitter :   @java9s

   facebook: www.facebook.com/java9s




www.JAVA9S.com

More Related Content

What's hot

Java: Inheritance
Java: InheritanceJava: Inheritance
Java: InheritanceTareq Hasan
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java yash jain
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7kamal kotecha
 
Java Inheritance
Java InheritanceJava Inheritance
Java InheritanceVINOTH R
 
Java non access modifiers
Java non access modifiersJava non access modifiers
Java non access modifiersSrinivas Reddy
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Sagar Verma
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Sagar Verma
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Uzair Salman
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers Hitesh-Java
 
Classes, objects, methods, constructors, this keyword in java
Classes, objects, methods, constructors, this keyword  in javaClasses, objects, methods, constructors, this keyword  in java
Classes, objects, methods, constructors, this keyword in javaTharuniDiddekunta
 

What's hot (20)

Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
inheritance
inheritanceinheritance
inheritance
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Java non access modifiers
Java non access modifiersJava non access modifiers
Java non access modifiers
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
 
Unit 3 Java
Unit 3 JavaUnit 3 Java
Unit 3 Java
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers
 
Classes, objects, methods, constructors, this keyword in java
Classes, objects, methods, constructors, this keyword  in javaClasses, objects, methods, constructors, this keyword  in java
Classes, objects, methods, constructors, this keyword in java
 

Viewers also liked

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
JDK 8, lambdas, streams, collectors - Bretagne Tour
JDK 8, lambdas, streams, collectors - Bretagne TourJDK 8, lambdas, streams, collectors - Bretagne Tour
JDK 8, lambdas, streams, collectors - Bretagne TourJosé Paumard
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdajMario Fusco
 
Autumn collection JavaOne 2014
Autumn collection JavaOne 2014Autumn collection JavaOne 2014
Autumn collection JavaOne 2014José Paumard
 
50 new things you can do with java 8
50 new things you can do with java 850 new things you can do with java 8
50 new things you can do with java 8José Paumard
 
Linked to ArrayList: the full story
Linked to ArrayList: the full storyLinked to ArrayList: the full story
Linked to ArrayList: the full storyJosé Paumard
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8José Paumard
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objectsrahulsahay19
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPTPooja Jaiswal
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
Bus Booking Management System
Bus Booking Management SystemBus Booking Management System
Bus Booking Management SystemMike Marshall
 
Bus Ticket Management System Documentation
Bus Ticket Management System DocumentationBus Ticket Management System Documentation
Bus Ticket Management System Documentationmuzammil siddiq
 
Online Bus Reservatiom System
Online Bus Reservatiom SystemOnline Bus Reservatiom System
Online Bus Reservatiom SystemNikhil Vyas
 
Online Bus Ticket Reservation System
Online Bus Ticket Reservation SystemOnline Bus Ticket Reservation System
Online Bus Ticket Reservation SystemTuvshinbayar Davaa
 

Viewers also liked (20)

Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
JDK 8, lambdas, streams, collectors - Bretagne Tour
JDK 8, lambdas, streams, collectors - Bretagne TourJDK 8, lambdas, streams, collectors - Bretagne Tour
JDK 8, lambdas, streams, collectors - Bretagne Tour
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdaj
 
Mobile based Bus Ticketing System
Mobile based Bus Ticketing SystemMobile based Bus Ticketing System
Mobile based Bus Ticketing System
 
Spring framework core
Spring framework coreSpring framework core
Spring framework core
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Autumn collection JavaOne 2014
Autumn collection JavaOne 2014Autumn collection JavaOne 2014
Autumn collection JavaOne 2014
 
50 new things you can do with java 8
50 new things you can do with java 850 new things you can do with java 8
50 new things you can do with java 8
 
Linked to ArrayList: the full story
Linked to ArrayList: the full storyLinked to ArrayList: the full story
Linked to ArrayList: the full story
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objects
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Bus Booking Management System
Bus Booking Management SystemBus Booking Management System
Bus Booking Management System
 
Bus Ticket Management System Documentation
Bus Ticket Management System DocumentationBus Ticket Management System Documentation
Bus Ticket Management System Documentation
 
Online Bus Reservatiom System
Online Bus Reservatiom SystemOnline Bus Reservatiom System
Online Bus Reservatiom System
 
Online Bus Ticket Reservation System
Online Bus Ticket Reservation SystemOnline Bus Ticket Reservation System
Online Bus Ticket Reservation System
 

Similar to Java Classes methods and inheritance

OOP with Java - Part 3
OOP with Java - Part 3OOP with Java - Part 3
OOP with Java - Part 3RatnaJava
 
Learn java
Learn javaLearn java
Learn javaPalahuja
 
OOP with Java - Part 3
OOP with Java - Part 3OOP with Java - Part 3
OOP with Java - Part 3Hitesh-Java
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satyaSatya Johnny
 
Session 09 - OOP with Java - Part 3
Session 09 - OOP with Java - Part 3Session 09 - OOP with Java - Part 3
Session 09 - OOP with Java - Part 3PawanMM
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application FrameworkJady Yang
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAVINASH KUMAR
 
3java Advanced Oop
3java Advanced Oop3java Advanced Oop
3java Advanced OopAdil Jafri
 
Do you really get class loaders?
Do you really get class loaders? Do you really get class loaders?
Do you really get class loaders? guestd56374
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming ConceptsBhushan Nagaraj
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingPurvik Rana
 
Java Interview Questions Answers Guide
Java Interview Questions Answers GuideJava Interview Questions Answers Guide
Java Interview Questions Answers GuideDaisyWatson5
 
Framework prototype
Framework prototypeFramework prototype
Framework prototypeDevMix
 
Framework prototype
Framework prototypeFramework prototype
Framework prototypeDevMix
 
Framework prototype
Framework prototypeFramework prototype
Framework prototypeDevMix
 
Class loader basic
Class loader basicClass loader basic
Class loader basic명철 강
 

Similar to Java Classes methods and inheritance (20)

OOP with Java - Part 3
OOP with Java - Part 3OOP with Java - Part 3
OOP with Java - Part 3
 
Learn java
Learn javaLearn java
Learn java
 
OOP with Java - Part 3
OOP with Java - Part 3OOP with Java - Part 3
OOP with Java - Part 3
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Session 09 - OOP with Java - Part 3
Session 09 - OOP with Java - Part 3Session 09 - OOP with Java - Part 3
Session 09 - OOP with Java - Part 3
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application Framework
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
3java Advanced Oop
3java Advanced Oop3java Advanced Oop
3java Advanced Oop
 
Do you really get class loaders?
Do you really get class loaders? Do you really get class loaders?
Do you really get class loaders?
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Inheritance1
Inheritance1Inheritance1
Inheritance1
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
Java Interview Questions Answers Guide
Java Interview Questions Answers GuideJava Interview Questions Answers Guide
Java Interview Questions Answers Guide
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 
Class loader basic
Class loader basicClass loader basic
Class loader basic
 

Recently uploaded

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Recently uploaded (20)

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

Java Classes methods and inheritance

  • 1. Classes, Methods and Inheritance SCJP / OCJP objectives : 1.1, 1.2, 1.3, 1.4, 5.5 By, www.JAVA9S.com Srinivas Reddy.S
  • 2. Declaring Classes Syntax: package com.java9s.ocjp; import com.sun.sample; class Car{ int speed;  State void move(){  behaviour //code related to move } } Save the file with Car.java.  If there are multiple classes in a file, the file name should be the name of the class with public access modifier. www.JAVA9S.com
  • 3. Declaring classes - Rules • The package statement should be the first statement in a file if the class belongs to a package. • Import statements comes next to package statement. • The order packageimportclass should be maintained. • Comments can come anywhere in the java file. • A java file can have any number of non public class files www.JAVA9S.com
  • 4. Declaring classes - Rules • package and import statements declared in a file apply to all the classes defined in the file. • A separate .class file will be generated for each class defined in the java file. • Any name can be given to a file when there is no public class declared in it. www.JAVA9S.com
  • 5. Creating Objects Car c = new Car(); Instantiation Declaration C is the reference which holds the Car Speed=50 memory address of the Car object C www.JAVA9S.com
  • 6. Creating Objects Car a = new Car(); a Car b = new Car(); b Car c = new Car(); c Car d = new Car(); d Car e = d; e d.speed =60; System.out.println(e.speed) ;-> 60 www.JAVA9S.com
  • 7. Methods • Methods are members of a class. • Methods have the behavior of an object. • Methods can be declared with or without arguments. • Two variants for a method: – Methods that return something – Methods that don’t return anything - void www.JAVA9S.com
  • 8. Methods – Return type Syntax: type methodName(arguments){ //code that decides the methods return x; } E.g., int addition(int a, int b){ int c = a+b; return c; } www.JAVA9S.com
  • 9. Methods – void type Syntax: void methodName(arguments){ //Method code.. No need to return anything. } E.g., void saveToFile(String message){ //Code related to saving message to file.. } www.JAVA9S.com
  • 10. Method – without argument Method with No arguments and with a return type: Date getCurrentDate(){ return Calender.get(Calender.DAY_OF_MONTH); } Method with no argument and no return type void printCurrentDate(){ System.out.println(Calendar.get(Calender.DAY_OF_MONTH)); } www.JAVA9S.com
  • 11. Inheritance • Inheritance is a way to reuse code from already existing types or objects. • Inheritance is implemented between two classes using extends keyword. • When a class extends another class, extending class is called subclass and extended class is super class. www.JAVA9S.com
  • 12. Inheritance class Car{ void move(){ •Car is super class System.out.println(“Moves”); •Ford is subclass. } } class Ford extends Car{ Ford f = new Ford(); f.moveFast(); void moveFast(){ f.move(); System.out.println(“Moves Fast”); } } www.JAVA9S.com
  • 13. Inheritance • With inheritance, all the members of super class are available to the subclass objects. • When a class extends another class, it has an IS-A relation with its super class. • instanceof keyword can be used to confirm IS-A relationship. www.JAVA9S.com
  • 14. Right or Wrong?? class Car{ } class Ford extends Car{ } class BMW extends Car{ } f instanceOf Car Ford f = new Ford(); f instanceOf BMW BMW b = new BMW(); Car c = new Car(); b instanceOf Ford b instanceOf Car c instanceOf Ford www.JAVA9S.com
  • 15. super and this keywords • super is used to access the super class members. • this is used to access the currently executing objects members. www.JAVA9S.com
  • 16. super - example class Car{ int speed; } class Ford extends Car{ int speed; void move(){ System.out.println(“Moving with car speed:”+super.speed) } } www.JAVA9S.com
  • 17. this - example class Ford{ int price; int price; setFordPrice(int price){ setFordPrice(int price){ this.price = price; this.price = price; } } } a Ford a = new Ford(); a.setFordPrice(3000); ‘this’ is not mandatory. But if you have local variables declared inside a method, to avoid confusion, this can be used to refer to members of the object. www.JAVA9S.com
  • 18. HAS-A relationship class Student{ Pen p = new Pen(); } class Pen{ } Student HAS-A pen. HAS – A relationship helps to reduce the complexity of the classes by the composition of the other classes. www.JAVA9S.com
  • 19. Thank you Follow me on to get more updates on latest video posts Subscribe on http://www.youtube.com/user/java9s Twitter : @java9s facebook: www.facebook.com/java9s www.JAVA9S.com