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

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
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
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
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
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
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
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
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 

Recently uploaded (20)

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
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
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
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
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
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
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
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 

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