SlideShare une entreprise Scribd logo
1  sur  22
Objectives


On completion of this period, you would be
able to learn
• Inner classes
• Using classes from other packages
• Importing packages




                                             1
Recap

Access protection
• To protect the access of members of an object
  • Done with the help of access modifiers
  • private, public, protected




                                                  2
Inner Classes
• Inner classes ?
   • We know what is nesting
   • Nested if
   • Nested looping
   • Nested blocks
   • Likewise, classes can also be nested
   • And such a class is an example of inner class


                                                     3
Inner Classes     Contd..
• Classes can be defined as members of other
  classes
• Classes can also be defined within a block of
  Java code
• Types
   • Member class
   • Local Class
   • Anonymous Class

                                                  4
Member Class
• A class defined as a member (non-static) of
  another
• Can use members of enclosing classes
• Cannot have static members
• Cannot have same name as a containing class




                                            5
Example
public class A {
  public String name = "a";
  public class B {
    public String name = "b";
    public class C {
      public String name = "c";
      public void print_names() {
        System.out.println(name); // "c": name field of class C
        System.out.println(this.name);// "c": name field of class C
        System.out.println(C.this.name);// "c": name field of class
    C
        System.out.println(B.this.name); // "b": name field of classB
        System.out.println(A.this.name);// "a": name field of class A
      }
    }
  }
}

                                                                6
Example Contd..

class Member Class Test {
   public static void main (String[] args ) {
        A a = new A();       // Create an instance of A.
        A.B b = a. new B(); // Create an instance of B within the
   instance of A.
        A.B.C c = b. new C(); // Create an instance of C within the
   instance of B.
        c. print _ names();     // Invoke a method of the instance of c.
   }                              Output
}




                                                                           7
Local Class

•   A class defined in a block of code
•   Can use members of enclosing classes
•   Cannot have static members
•   Cannot have same name as a containing class




                                                  8
Anonymous Class
•   Unnamed class defined within an expression
•   Can use members of enclosing classes
•   Cannot have static members
•   Cannot have same name as a containing class
•   Has no name or constructor
•   Only one instance of the class is created




                                                  9
Using Classes from Other Packages

• One of the 3 ways can be used:
  • Import the package member using import
    statement
  • Import the member's entire package using
    import statement
  • Refer to the member by its fully qualified
    name (without using import statement)



                                                 10
Importing Classes from Packages
• To use classes from other package, you need
  to import the package of those classes
• By default, all Java programs import the
  java.lang.* package
   • you can use classes like String and
     Integer inside the program even though
     you haven't imported any packages

• The import statement is used to import classes
  from packages
• There can be any number of import statements
  in a source file                             11
Importing Classes from Packages        Contd..

• The syntax of import statement is

           import <nameOfPackage>;

  • nameOfPackage is any user defined or
    system defined package name
  • eg. :
     • // Importing a class a Date class
     • import java. util. Date
     • // Importing all classes in java. util package
     • import java. util.*;
                                                    12
import javax.swing.*;
                              Example    Program
public class SumArray {
  public static void main( String            Output
  args[] ) {
   int a[] = { 1, 2, 3, 4, 5, 6};
   int total = 0;
     for ( int i = 0; i < a.length; i+
  +)
      total += a[ i ];

        OptionPane.showMessageDia            Importing entire
        log( null,    "Total of array        package
        elements: " + total, "Sum the
        Elements of an Array",
        JOptionPane.INFORMATION
        _MESSAGE );
         System.exit( 0 );
    }
                                                                13
}
Another Example Program
package MyPack;            Package in
public class Balance {     which                                 Test is other
    String name;           Balance class   package test;         package
    double bal;            is defined      import MyPack.Balance;
    public Balance(String n, double b)
    {                                                               Importing a
                                           class TestBalance { package member
        name = n;
                                             public static void main(String[ ] args)
      bal = b;
                                             {
  }
                                                 Balance test Bal=
    public void show() {                                    new Balance("J.
      if(bal<0)                                               J. Jaspers", 99.88);
      System .out.print("-->> ");               testBal.show();
      System.out.println(name + ": $" +       }
                                           }
         bal);
    }                                  Output
}


                                                                              14
Fully Qualified Name
• Another approach to use a class from other
  packages
• No import statement is used
• Fully Qualify the name of the class
• The following example illustrates:
  • public static void main(String[] args) {
  •      java.util.Date x = new java.util.Date();
  •      System.out.println(“Today’s Date : “+
    x.toString());                           Date class is
                                             fully qualified
     }
                                                          15
Example Program
package MyPack;                              package test;
                          Package in
public class Balance { which                                            Test is other
    String name;                             class TestBalance {        package
                          Balance class
    double bal;           is defined           public static void main(String[ ] args)
    public Balance(String n, double b)         {
    {                                              MyPack.Balance testBal =
        name = n;                                     new MyPack.Balance("J.
      bal = b;                                                J. Jaspers", 99.88);
  }                                               testBal.show();
    public void show() {                        }
      if(bal<0)                              }
                                                                  Fully qualifying class
      System.out.print("-->> ");
                                                                  name
      System.out.println(name + ": $" +
                                    Output
         bal);}}


                                                                                  16
Summary
• In this class we have discussed
   • Inner classes
   • Types of inner classes
   • Different ways of using a class from other
     package
   • Import statement
   • Some example programs




                                                  17
Frequently Asked Questions
1. What is inner class ?
2. List the types of inner classes
3. What are the different ways of using a class
   defined in other package?
4. Write a program in Java that illustrates the use of
   import statement




                                                    18
Quiz


1. Among the following which is NOT an inner
  class ?
   1. Member Class
   2. Local Class
   3. Implicit Class
   4. Anonymous Class




                                           19
Quiz             Contd..




2. Which package is imported by default ?
   1. java. util.*
   2. java. lang.*
   3. java. sql.*
   4. java. net.*




                                             20
Quiz         Contd..




3. How many import statements can a Java
  class contain?

  1. Only one
  2. Two
  3. Three
  4. Zero or more



                                           21
Quiz              Contd..




4. Which of the following class has no name ?
   Member Class
   Anonymous Class
   Local Class
   Inner Class




                                             22

Contenu connexe

Tendances

Tendances (20)

Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
Taming Java Agents
Taming Java AgentsTaming Java Agents
Taming Java Agents
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
 
Java session4
Java session4Java session4
Java session4
 
Java class
Java classJava class
Java class
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interface
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statement
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 

En vedette

9 Lessons I Learned Starting Science Exchange
9 Lessons I Learned Starting Science Exchange9 Lessons I Learned Starting Science Exchange
9 Lessons I Learned Starting Science Exchange
Science Exchange
 
9 dávila construcción sociocultural de la obesidad
9 dávila construcción sociocultural de la obesidad9 dávila construcción sociocultural de la obesidad
9 dávila construcción sociocultural de la obesidad
LESGabriela
 
Boat enviromentalist
Boat enviromentalistBoat enviromentalist
Boat enviromentalist
santi1831
 
9 d1075 v_n_v_madhav
9 d1075 v_n_v_madhav9 d1075 v_n_v_madhav
9 d1075 v_n_v_madhav
Zahn Ärztin
 
9 d seguimiento segundo periodo mayo 22 de 2013
9 d seguimiento segundo periodo  mayo 22 de 20139 d seguimiento segundo periodo  mayo 22 de 2013
9 d seguimiento segundo periodo mayo 22 de 2013
IE Simona Duque
 
9 Degrees of Freedom LSM9DS0
9 Degrees of Freedom LSM9DS09 Degrees of Freedom LSM9DS0
9 Degrees of Freedom LSM9DS0
Karyn Cole
 
9. antecedentes... letra
9. antecedentes... letra9. antecedentes... letra
9. antecedentes... letra
Isaac Lara
 

En vedette (19)

9. Success in Cross-Cultural Business--Links--Addendum
9. Success in Cross-Cultural Business--Links--Addendum9. Success in Cross-Cultural Business--Links--Addendum
9. Success in Cross-Cultural Business--Links--Addendum
 
Enlace Ciudadano Nro. 229 - Desempleo
Enlace Ciudadano Nro. 229 -  DesempleoEnlace Ciudadano Nro. 229 -  Desempleo
Enlace Ciudadano Nro. 229 - Desempleo
 
9 fundraising mapping bokal
9 fundraising mapping bokal9 fundraising mapping bokal
9 fundraising mapping bokal
 
porttaa
porttaaporttaa
porttaa
 
9-July-2014 Open Source Software Panel - Google Summer of Code & Code-In intr...
9-July-2014 Open Source Software Panel - Google Summer of Code & Code-In intr...9-July-2014 Open Source Software Panel - Google Summer of Code & Code-In intr...
9-July-2014 Open Source Software Panel - Google Summer of Code & Code-In intr...
 
9 Lessons I Learned Starting Science Exchange
9 Lessons I Learned Starting Science Exchange9 Lessons I Learned Starting Science Exchange
9 Lessons I Learned Starting Science Exchange
 
C&C studio September schedule
C&C studio September scheduleC&C studio September schedule
C&C studio September schedule
 
Life Leadership: Nine Leaping Thoughts
Life Leadership: Nine Leaping ThoughtsLife Leadership: Nine Leaping Thoughts
Life Leadership: Nine Leaping Thoughts
 
Hosted CRM, Hosted IPT, Home Office... ¡una fórmula exitosa!
Hosted CRM, Hosted IPT, Home Office... ¡una fórmula exitosa!Hosted CRM, Hosted IPT, Home Office... ¡una fórmula exitosa!
Hosted CRM, Hosted IPT, Home Office... ¡una fórmula exitosa!
 
9 dávila construcción sociocultural de la obesidad
9 dávila construcción sociocultural de la obesidad9 dávila construcción sociocultural de la obesidad
9 dávila construcción sociocultural de la obesidad
 
9.invitacion coneoup(arequipa2014)
9.invitacion coneoup(arequipa2014)9.invitacion coneoup(arequipa2014)
9.invitacion coneoup(arequipa2014)
 
9 Điều Cần Nhớ Trong Cuộc Sống
9 Điều Cần Nhớ Trong Cuộc Sống9 Điều Cần Nhớ Trong Cuộc Sống
9 Điều Cần Nhớ Trong Cuộc Sống
 
9 Key Takeaways for Brands from WOMMA Summit 2012
9 Key Takeaways for Brands from WOMMA Summit 20129 Key Takeaways for Brands from WOMMA Summit 2012
9 Key Takeaways for Brands from WOMMA Summit 2012
 
Boat enviromentalist
Boat enviromentalistBoat enviromentalist
Boat enviromentalist
 
9 d1075 v_n_v_madhav
9 d1075 v_n_v_madhav9 d1075 v_n_v_madhav
9 d1075 v_n_v_madhav
 
9 d seguimiento segundo periodo mayo 22 de 2013
9 d seguimiento segundo periodo  mayo 22 de 20139 d seguimiento segundo periodo  mayo 22 de 2013
9 d seguimiento segundo periodo mayo 22 de 2013
 
9. la-conferencia
9. la-conferencia9. la-conferencia
9. la-conferencia
 
9 Degrees of Freedom LSM9DS0
9 Degrees of Freedom LSM9DS09 Degrees of Freedom LSM9DS0
9 Degrees of Freedom LSM9DS0
 
9. antecedentes... letra
9. antecedentes... letra9. antecedentes... letra
9. antecedentes... letra
 

Similaire à 9 cm604.28

Using classes from other packages
Using classes from other packagesUsing classes from other packages
Using classes from other packages
myrajendra
 
Java class 3
Java class 3Java class 3
Java class 3
Edureka!
 
Class loader basic
Class loader basicClass loader basic
Class loader basic
명철 강
 
Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]
Palak Sanghani
 
Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)
Abhishek Khune
 

Similaire à 9 cm604.28 (20)

Using classes from other packages
Using classes from other packagesUsing classes from other packages
Using classes from other packages
 
7.Packages and Interfaces(MB).ppt .
7.Packages and Interfaces(MB).ppt             .7.Packages and Interfaces(MB).ppt             .
7.Packages and Interfaces(MB).ppt .
 
Java class 3
Java class 3Java class 3
Java class 3
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part III
 
Java packages
Java packagesJava packages
Java packages
 
OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access ModifiersOOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Packages and interface
Packages and interfacePackages and interface
Packages and interface
 
Class loader basic
Class loader basicClass loader basic
Class loader basic
 
Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]
 
Packages
PackagesPackages
Packages
 
Constructors in JAva.pptx
Constructors in JAva.pptxConstructors in JAva.pptx
Constructors in JAva.pptx
 
UNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxUNIT_-II_2021R.pptx
UNIT_-II_2021R.pptx
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Package.pptx
Package.pptxPackage.pptx
Package.pptx
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
 
Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packages
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)
 
20-packages-jar.ppt
20-packages-jar.ppt20-packages-jar.ppt
20-packages-jar.ppt
 

Plus de myrajendra (20)

Fundamentals
FundamentalsFundamentals
Fundamentals
 
Data type
Data typeData type
Data type
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Jdbc workflow
Jdbc workflowJdbc workflow
Jdbc workflow
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Dao example
Dao exampleDao example
Dao example
 
Sessionex1
Sessionex1Sessionex1
Sessionex1
 
Internal
InternalInternal
Internal
 
3. elements
3. elements3. elements
3. elements
 
2. attributes
2. attributes2. attributes
2. attributes
 
1 introduction to html
1 introduction to html1 introduction to html
1 introduction to html
 
Headings
HeadingsHeadings
Headings
 
Forms
FormsForms
Forms
 
Css
CssCss
Css
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Starting jdbc
Starting jdbcStarting jdbc
Starting jdbc
 

9 cm604.28

  • 1. Objectives On completion of this period, you would be able to learn • Inner classes • Using classes from other packages • Importing packages 1
  • 2. Recap Access protection • To protect the access of members of an object • Done with the help of access modifiers • private, public, protected 2
  • 3. Inner Classes • Inner classes ? • We know what is nesting • Nested if • Nested looping • Nested blocks • Likewise, classes can also be nested • And such a class is an example of inner class 3
  • 4. Inner Classes Contd.. • Classes can be defined as members of other classes • Classes can also be defined within a block of Java code • Types • Member class • Local Class • Anonymous Class 4
  • 5. Member Class • A class defined as a member (non-static) of another • Can use members of enclosing classes • Cannot have static members • Cannot have same name as a containing class 5
  • 6. Example public class A { public String name = "a"; public class B { public String name = "b"; public class C { public String name = "c"; public void print_names() { System.out.println(name); // "c": name field of class C System.out.println(this.name);// "c": name field of class C System.out.println(C.this.name);// "c": name field of class C System.out.println(B.this.name); // "b": name field of classB System.out.println(A.this.name);// "a": name field of class A } } } } 6
  • 7. Example Contd.. class Member Class Test { public static void main (String[] args ) { A a = new A(); // Create an instance of A. A.B b = a. new B(); // Create an instance of B within the instance of A. A.B.C c = b. new C(); // Create an instance of C within the instance of B. c. print _ names(); // Invoke a method of the instance of c. } Output } 7
  • 8. Local Class • A class defined in a block of code • Can use members of enclosing classes • Cannot have static members • Cannot have same name as a containing class 8
  • 9. Anonymous Class • Unnamed class defined within an expression • Can use members of enclosing classes • Cannot have static members • Cannot have same name as a containing class • Has no name or constructor • Only one instance of the class is created 9
  • 10. Using Classes from Other Packages • One of the 3 ways can be used: • Import the package member using import statement • Import the member's entire package using import statement • Refer to the member by its fully qualified name (without using import statement) 10
  • 11. Importing Classes from Packages • To use classes from other package, you need to import the package of those classes • By default, all Java programs import the java.lang.* package • you can use classes like String and Integer inside the program even though you haven't imported any packages • The import statement is used to import classes from packages • There can be any number of import statements in a source file 11
  • 12. Importing Classes from Packages Contd.. • The syntax of import statement is import <nameOfPackage>; • nameOfPackage is any user defined or system defined package name • eg. : • // Importing a class a Date class • import java. util. Date • // Importing all classes in java. util package • import java. util.*; 12
  • 13. import javax.swing.*; Example Program public class SumArray { public static void main( String Output args[] ) { int a[] = { 1, 2, 3, 4, 5, 6}; int total = 0; for ( int i = 0; i < a.length; i+ +) total += a[ i ]; OptionPane.showMessageDia Importing entire log( null, "Total of array package elements: " + total, "Sum the Elements of an Array", JOptionPane.INFORMATION _MESSAGE ); System.exit( 0 ); } 13 }
  • 14. Another Example Program package MyPack; Package in public class Balance { which Test is other String name; Balance class package test; package double bal; is defined import MyPack.Balance; public Balance(String n, double b) { Importing a class TestBalance { package member name = n; public static void main(String[ ] args) bal = b; { } Balance test Bal= public void show() { new Balance("J. if(bal<0) J. Jaspers", 99.88); System .out.print("-->> "); testBal.show(); System.out.println(name + ": $" + } } bal); } Output } 14
  • 15. Fully Qualified Name • Another approach to use a class from other packages • No import statement is used • Fully Qualify the name of the class • The following example illustrates: • public static void main(String[] args) { • java.util.Date x = new java.util.Date(); • System.out.println(“Today’s Date : “+ x.toString()); Date class is fully qualified } 15
  • 16. Example Program package MyPack; package test; Package in public class Balance { which Test is other String name; class TestBalance { package Balance class double bal; is defined public static void main(String[ ] args) public Balance(String n, double b) { { MyPack.Balance testBal = name = n; new MyPack.Balance("J. bal = b; J. Jaspers", 99.88); } testBal.show(); public void show() { } if(bal<0) } Fully qualifying class System.out.print("-->> "); name System.out.println(name + ": $" + Output bal);}} 16
  • 17. Summary • In this class we have discussed • Inner classes • Types of inner classes • Different ways of using a class from other package • Import statement • Some example programs 17
  • 18. Frequently Asked Questions 1. What is inner class ? 2. List the types of inner classes 3. What are the different ways of using a class defined in other package? 4. Write a program in Java that illustrates the use of import statement 18
  • 19. Quiz 1. Among the following which is NOT an inner class ? 1. Member Class 2. Local Class 3. Implicit Class 4. Anonymous Class 19
  • 20. Quiz Contd.. 2. Which package is imported by default ? 1. java. util.* 2. java. lang.* 3. java. sql.* 4. java. net.* 20
  • 21. Quiz Contd.. 3. How many import statements can a Java class contain? 1. Only one 2. Two 3. Three 4. Zero or more 21
  • 22. Quiz Contd.. 4. Which of the following class has no name ? Member Class Anonymous Class Local Class Inner Class 22