SlideShare uma empresa Scribd logo
1 de 58
Chapter 5



Introduction To Class



                   http://www.java2all.com
What is class?
•    Class is a collection of data members and
    member functions.

Now what are data members?
•      Data members are nothing but simply
  variables that we declare inside the class so it
  called data member of that particular class.


                                           http://www.java2all.com
Now what are member functions?
            Member functions are the function
  or you can say methods which we declare
  inside the class so it called member function
  of that particular class. The most important
  thing to understand about a class is that it
  defines a new data type. Once defined, this
  new type can be used to create objects of that
  type. Thus, a class is a template for an object,
  and an object is an instance of a class.
  Because an object is an instance of a class, you
  will often see the two words object and
  instance used interchangeably.
                                            http://www.java2all.com
Syntax of class:
class classname
{      type instance-variable;
       type methodname1(parameter-list)
      {
             // body of method
      }
      type methodname2(parameter-list)
      {
             // body of method
      }
}                                         http://www.java2all.com
•      When you define a class, you declare its exact
    form and nature. You do this by specifying the data
    that it contains and the code that operates on that
    data.

•       The data, or variables, defined within a class are
    called instance variables. The code is contained
    within methods.

• NOTE : C++ programmers will notice that the class
  declaration and the implementation of the methods
  are stored in the same place and not defined
  separately.                               http://www.java2all.com
Example :
public class MyPoint
{
    int x = 0;
    int y = 0;
     void displayPoint()
    {
         System.out.println("Printing the coordinates");
         System.out.println(x + " " + y);
    }

    public static void main(String args[])
    {
        MyPoint obj;           // declaration
        obj = new MyPoint();             // allocation of memory to an object
        obj.x=10;             //access data member using object.
        obj.y=20;
        obj.displayPoint(); // calling a member method
    }
}
                                                                                http://www.java2all.com
Syntax:
accessing data member of the class:
 objectname.datamember name;

accessing methods of the class:
 objectname.methodname();

So for accessing data of the class:
we have to use (.) dot operator.
NOTE: we can use or access data of any particular
  class without using (.) dot operator from inside that
  particular class only.                      http://www.java2all.com
Creating Our
    First
Class Object


               http://www.java2all.com
Creating Our First Class Object

             The program we gave in previous topic from that
we can easily learn that how object is going to declare and
define for any class.




                                                 http://www.java2all.com
Syntax of object:

classname objectname;         declaration of object.
objectname = new classname();
  allocate memory to object (define object).

or we can directly define object like this

classname objectname = new classname();


                                             http://www.java2all.com
import java.text.DecimalFormat;

public class Time1 extends Object
{
   private int hour;     // 0 - 23
   private int minute;   // 0 - 59
   private int second;   // 0 - 59

  public Time1()            We would use this class to
  {
     setTime( 0, 0, 0 );    display the time, and control
  }                         how the user changed it.
  public void   setTime( int h, int m, int s )
  {
     hour = (   ( h >= 0 && h < 24 ) ? h : 0 );
     minute =   ( ( m >= 0 && m < 60 ) ? m : 0 );
     second =   ( ( s >= 0 && s < 60 ) ? s : 0 );
  }



                                                    http://www.java2all.com
import java.text.DecimalFormat;

public class Time1 extends Object
{
   private int hour;     // 0 - 23
   private int minute;   // 0 - 59
   private int second;   // 0 - 59

  public Time1()
  {
     setTime( 0, 0, 0 );
  }

  public void setTime( int h, int m, int s )
  {    We can only have one public class per file.
     hour = ( class >= 0 && be < 24 ) in h : 0 called
        This ( h would h stored ? a file );
     minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
                      “Time1.java.”
     second = ( ( s >= 0 && s < 60 ) ? s : 0 );
  Question: Does that mean we can include other classes
  }
       in our file—if they are not declared public?
                                                http://www.java2all.com
import java.text.DecimalFormat;

public class Time1 extends Object
{
   private int hour;     // 0 - 23
   private int minute;   // 0 - 59
   private int second;   // 0 - 59

  public Time1()
  {
     setTime( 0, 0, 0 );
  }  In keeping with encapsulation, the member-
   access modifiers declare our instance variables
   public void setTime( int h, int m, int s )
   {                     private.
      hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
   When this ( ( m >= 0 && m < 60 ) ? m the only way
      minute = class gets instantiated, : 0 );
  to access = ( ( svariables is through :the);
      second these >= 0 && s < 60 ) ? s     0 methods
   }
                       of the class.
                                             http://www.java2all.com
import java.text.DecimalFormat;

public class Time1 extends Object
{                                    The Constructor
   private int hour;     // 0 - 23   method “ Time1()”
   private int minute;   // 0 - 59
   private int second;   // 0 - 59   must have the same
                                     name as the class so
  public Time1()
  {
                                     the compiler always
     setTime( 0, 0, 0 );             knows how to
  }                                  initialize the class.
  public void   setTime( int h, int m, int s )
  {
     hour = (   ( h >= 0 && h < 24 ) ? h : 0 );
     minute =   ( ( m >= 0 && m < 60 ) ? m : 0 );
     second =   ( ( s >= 0 && s < 60 ) ? s : 0 );
  }



                                                    http://www.java2all.com
import java.text.DecimalFormat;in
The method setTime()takes          the time arguments. It
validates the Time1 extends Objectseconds to make sure they
public class hours, minutes and
make sense. Now you can see why the concept of a class
{
   private int hour;      // 0 - 23
might be prettyminute; // 0 - 59
   private int
                 nifty.
   private int second;     // 0 - 59

   public Time1()
   {
      setTime( 0, 0, 0 );
   }

   public void   setTime( int h, int m, int s )
   {
      hour = (   ( h >= 0 && h < 24 ) ? h : 0 );
      minute =   ( ( m >= 0 && m < 60 ) ? m : 0 );
      second =   ( ( s >= 0 && s < 60 ) ? s : 0 );
   }



                                                     http://www.java2all.com
Using Our New Class


• We cannot instantiate it in this class.


• We need to create another class to do actually make an
example of this class.




                                                http://www.java2all.com
Using Our New Class
• We need to create a driver program TimeTest.java


• The only purpose of this new class is to instantiate and
test our new class Time1.




                                                 http://www.java2all.com
Introduction To Method




                         http://www.java2all.com
•      As we all know that, classes usually consist of
    two things instance variables and methods.
•      Here we are going to explain some
    fundamentals about methods.
•      So we can begin to add methods to our classes.
•      Methods are defined as follows
•      § Return type
•      § Name of the method
•      § A list of parameters
•      § Body of the method.


                                             http://www.java2all.com
Syntax:
return type method name (list of parameters)
{
         Body of the method
}

• return type specifies the type of data returned by
  the method. This can be any valid data type
  including class types that you create.
• If the method does not return a value, its return
  type must be void, Means you can say that void
  means no return.                            http://www.java2all.com
• Methods that have a return type other than void
  return a value to the calling routine using the
  following form of the return statement:
• return value;
  Here, value is the value returned.
• The method name is any legal identifier.
• The list of parameter is a sequence of type and
  identifier pairs separated by commas. Parameters
  are essentially variables that receive the value of
  the arguments passed to the method when it is
  called.
• If the method has no parameters, then the
  parameter list will be empty.                http://www.java2all.com
import java.util.Scanner;
class Box
{
    double width;
    double height;
    double depth;
    void volume()       // display volume of a box
    {
        System.out.print("Volume is : ");
        System.out.println(width * height * depth);
    }
}
class BoxDemo
{
    public static void main(String args[])
   {
        Box box1 = new Box(); // defining object box1 of class Box
        Scanner s = new Scanner(System.in);
        System.out.print(“Enter Box Width : ”);
        box1.width = s.nextDouble();
        System.out.print(“Enter Box Height : ”);
        box1.height = s.nextDouble();
        System.out.print(“Enter Box Depth : ”);
        box1.depth = s.nextDouble();
        // display volume of box1
        box1.volume(); // calling the method volume
    }
}                                                                    http://www.java2all.com
Constructors




               http://www.java2all.com
Constructors

• The Constructor is named exactly the same as
the class.


• The Constructor is called when the new
keyword is used.


• The Constructor cannot have any return type —
not even void.


                                             http://www.java2all.com
Constructors
• The Constructor instantiates the object.


• It initializes instance variables to acceptable values.


• The “default” Constructor accepts no arguments.


• The Constructor method is usually overloaded.


                                                   http://www.java2all.com
Varieties of Methods: Constructors

• The overloaded Constructor usually takes arguments.

• That allows the class to be instantiated in a variety of
ways.

• If the designer neglects to include a constructor, then the
compiler creates a default constructor that takes no
arguments.

• A default constructor will call the Constructor for the
class this one extends.

                                                   http://www.java2all.com
public Time2()
{
      setTime( 0, 0, 0 );
}




  • This is the first Constructor.

  • Notice that it takes no arguments, but it still sets the
  instance variables for hour, minute and second to
  consistent initial values of zero.




                                                       http://www.java2all.com
public Time2()
{
      setTime( 0, 0, 0 );
}

public Time2( int h, int m, int s )
{
      setTime( h, m, s );
}

• These are the first two Constructors.

• The second one overrides the first.

• The second Constructor takes arguments.

• It still calls the setTime() method so it can validate
the data.
                                                  http://www.java2all.com
public Time2()
{
      setTime( 0, 0, 0 );
}         Usually, we can’t directly access the
           private instance variables of an
public Time2( int h, int m, int s )
{              object, because it violates
      setTime( h, m, encapsulation.
                      s );
}
        However, objects of the same class are
public Time2( Time2 time access each other’s
           permitted to )
{
              instance variables directly.
      setTime( time.hour, time.minute, time.second         );
}
    • This final constructor is quite interesting.

    • It takes as an argument a Time2 object.

    • This will make the two Time2 objects equal.
                                                     http://www.java2all.com
public class Employee extends Object
{ private String firstName;
   private String lastName;
   private static int count; // # of objects in memory

    public Employee( String fName, String lName )
    { firstName = fName;
       lastName = lName;
       ++count; // increment static count of employees
       System.out.println( "Employee object constructor: " +
                           firstName + " " + lastName );
    }

    protected void finalize()    Because count is declared
                                 as private static, the
    { —count; // decrement static count of employees
       System.out.println( "Employee object finalizer: " +
                           firstName + " " + to access +
                                  only way lastName its data
                           "; count = "by count ); public
                                    is + using a
    }
                                      static method.
    public String getFirstName() { return firstName; }
    public String getLastName() { return lastName; }
    public static int getCount() { return count; }
}
                                                         http://www.java2all.com
public class Employee extends Object
{ private String firstName;
   private String lastName;
   private static int count; // # of objects in memory

    public Employee( String fName, String lName )
    { firstName = fName;
       lastName = lName;
       ++count; // increment static count of employees
       System.out.println( "Employee object constructor: " +
                           firstName + " " + lastName );
    }

    protected void finalize()
    { —count; // decrement static count of employees
       System.out.println( "Employee object finalizer: " +
                           firstName + " " + lastName +
                           "; count = " + count );
    }

    public String getFirstName() { return firstName; }
    public String getLastName() { return lastName; }
    public static int getCount() { return count; }
}
                                                         http://www.java2all.com
Access
Modifiers



            http://www.java2all.com
Superclasses and Subclasses
 Impact on Access Modifiers

 • Access Modifiers are among the thorniest and
 most confusing aspects of OOP.


 • But, remember, encapsulation is one of the
 primary benefits of object orientation, so access is
 important.



                                              http://www.java2all.com
Superclasses and Subclasses

 Impact on Access Modifiers

 • The familiar private access modifier lets us
 shield our instance variables from the prying eyes
 of the outside world.

 • Relying on Access Modifiers, you can shield both
 your class’s private instance variables and its
 private methods.


                                            http://www.java2all.com
Superclasses and Subclasses
 Impact on Access Modifiers
 • With those ends in mind, Java lets review the four
 different levels of access:

 private,

        protected,

                        public

  and the default if you don’t specify   package.

                                                    http://www.java2all.com
Superclasses and Subclasses

 • A summary of the various types of access
 modifier:


 Specifier class       subclass package world
 private   X
 package    X                    X
 protected X           X         X
 public     X          X         X            X


                                          http://www.java2all.com
Superclasses and Subclasses

 • As you can see, a class always has access to its
 own instance variables, with any access modifier.

 Specifier class       subclass package world
 private   X
 package    X                     X
 protected X           X          X
 public     X          X          X             X



                                            http://www.java2all.com
Superclasses and Subclasses

• The second column shows that Subclasses of this
class (no matter what package they are in) have access
to public (obviously) and protected variables.


 Specifier class      subclass package       world
 private X
 package X                       X
 protected X          X          X
 public X             X          X          X

                                            http://www.java2all.com
• Therefore, the important point?

Subclasses can reach protected-access variables,
but can’t reach package-access variables…

unless the Subclasses happen to be saved in the
same package.



                                           http://www.java2all.com
Superclasses and Subclasses
• The third column “package” shows that classes in
the same package as the class (regardless of their
parentage) have access to data variables.


 Specifier   class   subclass package       world
 private     X
 package     X                  X
 protected   X       X          X
 public      X       X          X          X

                                           http://www.java2all.com
Superclasses and Subclasses

 • In the fourth column, we see that anything and
 anyone has access to a public data variable or
 method—defeating the purpose of encapsulation.

 Specifier   class    subclass   package world
 private     X
 package     X                   X
 protected   X         X         X
 public      X         X         X            X

                                          http://www.java2all.com
private




          http://www.java2all.com
Superclasses and Subclasses
 Impact on Access Modifiers: private

 • When my class inherits from a Superclass, I
 cannot access the Superclass’s private data
 variables. Private data is Secret!

 • In other words, the Subclass cannot automatically
 reach the private data variables of the Superclass.

 • A private data variable is accessible only to the
 class in which it is defined.

                                              http://www.java2all.com
Objects of type Alpha can inspect or modify the
    iamprivate variable and can call privateMethod,
    but objects of any other type cannot.
class Alpha
{
     private int iamprivate;

       public Alpha( int iam )
       {
            iamprivate = iam;
       }

       private void privateMethod()
       {
          iamprivate = 2;
          System.out.println(“” + iamprivate);
       }
}                                            http://www.java2all.com
The Beta class, for example, cannot access the
iamprivate variable or invoke privateMethod on an
object of type Alpha because Beta is not of type Alpha .

class Beta
{
     public void accessMethod()
     {
          Alpha a = new Alpha();
          a.iamprivate = 10; // Invalid
          a.privateMethod(); // Invalid
     }
}


• The compiler would complain if you tried this.
                                                   http://www.java2all.com
Can one instance of an Alpha object access the
private data variables of another instance of an
Alpha object?

                 Yes!
Objects of the same type have access to one
another’s private members.




                                              http://www.java2all.com
package




          http://www.java2all.com
Superclasses and Subclasses
 Varieties of Access Modifiers: package

 • If you do not specify the access for either a
 method or an encapsulated data variable, then it is
 given the default access:

            package



                                             http://www.java2all.com
Superclasses and Subclasses
 Varieties of Access Modifiers: package

 • This access allows other classes in the same
 package as your class to access its data variables as
 if they were their own.
            package
 • This level of access assumes that classes in the
 same package as your class are friends who won’t
 harm your class’ data.

                                             http://www.java2all.com
• Notice that no access modifier is declared.
 So, iamprivate and method privateMethod
 both default to package access.
 • All classes declared in the package Greek, along
 with class Delta, have access to iamprivate and
 privateMethod.
package Greek;
class Delta
{
     int iamprivate;
     void privateMethod()
     {
          System.out.println(“privateMethod”);
     }
}
Superclasses and Subclasses
 Varieties of Access Modifiers: package

            package
 • If you use multiple objects from the same
 package, they can access each other’s package-
 access methods and data variables directly, merely
 by referencing an object that has been instantiated.




                                             http://www.java2all.com
Superclasses and Subclasses
 Varieties of Access Modifiers: package

            package
 • With package access, other objects in the package
 don’t have to bother going through the methods.

 They can get right to the variables.




                                            http://www.java2all.com
Superclasses and Subclasses


• So, when you don’t include any access modifier,
you are in fact giving your variable package
access.

      int x;    // package access instance variable




• Notice, it’s declared neither public nor
private.


                                             http://www.java2all.com
protected




            http://www.java2all.com
Superclasses and Subclasses


 • protected allows the class itself, Subclasses
 and all classes in the same package to access the
 members.

 • Generally speaking, protected offers greater
 access than package access.




                                            http://www.java2all.com
Superclasses and Subclasses
 • Use the protected access level when it’s
 appropriate for a class’s Subclasses to have access
 to the member, but not for unrelated classes to have
 access.


 • protected members are like family secrets—
 you don’t mind if someone in the family knows—
 but you don’t want outsiders to know.



                                            http://www.java2all.com
Superclasses and Subclasses

 • The Access Modifier protected can be used
 on either a method or an encapsulated data
 variable.

 • protected serves as a middle ground
 between the private and public access
 modifier.




                                      http://www.java2all.com
Superclasses and Subclasses

• A Superclass’s protected data variables may be
accessed only by:

     —methods of the Superclass
     —methods of the Subclass
     —methods of other classes in the same package.

Or we can summarize:

     protected members have package access.

                                         http://www.java2all.com

Mais conteúdo relacionado

Mais procurados

class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Control structures in java
Control structures in javaControl structures in java
Control structures in javaVINOTH R
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of ConstructorsDhrumil Panchal
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in javaHitesh Kumar
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Function template
Function templateFunction template
Function templateKousalya M
 
Friend functions
Friend functions Friend functions
Friend functions Megha Singh
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Kamlesh Makvana
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oopsHirra Sultan
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in javasawarkar17
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member FunctionsMuhammad Hammad Waseem
 

Mais procurados (20)

class and objects
class and objectsclass and objects
class and objects
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Control statements in java programmng
Control statements in java programmngControl statements in java programmng
Control statements in java programmng
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Function template
Function templateFunction template
Function template
 
Friend functions
Friend functions Friend functions
Friend functions
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 

Semelhante a Introduction to class in java

Class & Objects in JAVA.ppt
Class & Objects in JAVA.pptClass & Objects in JAVA.ppt
Class & Objects in JAVA.pptRohitPaul71
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of javakamal kotecha
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMambikavenkatesh2
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08Terry Yoast
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaRadhika Talaviya
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 
Object oriented design
Object oriented designObject oriented design
Object oriented designlykado0dles
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 

Semelhante a Introduction to class in java (20)

oops-1
oops-1oops-1
oops-1
 
Unit i
Unit iUnit i
Unit i
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Class & Objects in JAVA.ppt
Class & Objects in JAVA.pptClass & Objects in JAVA.ppt
Class & Objects in JAVA.ppt
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Java sessionnotes
Java sessionnotesJava sessionnotes
Java sessionnotes
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Closer look at classes
Closer look at classesCloser look at classes
Closer look at classes
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoM
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Chap08
Chap08Chap08
Chap08
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Object oriented design
Object oriented designObject oriented design
Object oriented design
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Core java oop
Core java oopCore java oop
Core java oop
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Chapter iii(oop)
Chapter iii(oop)Chapter iii(oop)
Chapter iii(oop)
 

Mais de kamal kotecha

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with codekamal kotecha
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7kamal kotecha
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operatorkamal kotecha
 

Mais de kamal kotecha (20)

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
 
Java rmi
Java rmiJava rmi
Java rmi
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
Jsp element
Jsp elementJsp element
Jsp element
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Interface
InterfaceInterface
Interface
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
Class method
Class methodClass method
Class method
 
Control statements
Control statementsControl statements
Control statements
 
Jsp myeclipse
Jsp myeclipseJsp myeclipse
Jsp myeclipse
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 

Último

Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 

Último (20)

Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 

Introduction to class in java

  • 1. Chapter 5 Introduction To Class http://www.java2all.com
  • 2. What is class? • Class is a collection of data members and member functions. Now what are data members? • Data members are nothing but simply variables that we declare inside the class so it called data member of that particular class. http://www.java2all.com
  • 3. Now what are member functions? Member functions are the function or you can say methods which we declare inside the class so it called member function of that particular class. The most important thing to understand about a class is that it defines a new data type. Once defined, this new type can be used to create objects of that type. Thus, a class is a template for an object, and an object is an instance of a class. Because an object is an instance of a class, you will often see the two words object and instance used interchangeably. http://www.java2all.com
  • 4. Syntax of class: class classname { type instance-variable; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method } } http://www.java2all.com
  • 5. When you define a class, you declare its exact form and nature. You do this by specifying the data that it contains and the code that operates on that data. • The data, or variables, defined within a class are called instance variables. The code is contained within methods. • NOTE : C++ programmers will notice that the class declaration and the implementation of the methods are stored in the same place and not defined separately. http://www.java2all.com
  • 6. Example : public class MyPoint { int x = 0; int y = 0; void displayPoint() { System.out.println("Printing the coordinates"); System.out.println(x + " " + y); } public static void main(String args[]) { MyPoint obj; // declaration obj = new MyPoint(); // allocation of memory to an object obj.x=10; //access data member using object. obj.y=20; obj.displayPoint(); // calling a member method } } http://www.java2all.com
  • 7. Syntax: accessing data member of the class: objectname.datamember name; accessing methods of the class: objectname.methodname(); So for accessing data of the class: we have to use (.) dot operator. NOTE: we can use or access data of any particular class without using (.) dot operator from inside that particular class only. http://www.java2all.com
  • 8. Creating Our First Class Object http://www.java2all.com
  • 9. Creating Our First Class Object The program we gave in previous topic from that we can easily learn that how object is going to declare and define for any class. http://www.java2all.com
  • 10. Syntax of object: classname objectname; declaration of object. objectname = new classname(); allocate memory to object (define object). or we can directly define object like this classname objectname = new classname(); http://www.java2all.com
  • 11. import java.text.DecimalFormat; public class Time1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 public Time1() We would use this class to { setTime( 0, 0, 0 ); display the time, and control } how the user changed it. public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } http://www.java2all.com
  • 12. import java.text.DecimalFormat; public class Time1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 public Time1() { setTime( 0, 0, 0 ); } public void setTime( int h, int m, int s ) { We can only have one public class per file. hour = ( class >= 0 && be < 24 ) in h : 0 called This ( h would h stored ? a file ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); “Time1.java.” second = ( ( s >= 0 && s < 60 ) ? s : 0 ); Question: Does that mean we can include other classes } in our file—if they are not declared public? http://www.java2all.com
  • 13. import java.text.DecimalFormat; public class Time1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 public Time1() { setTime( 0, 0, 0 ); } In keeping with encapsulation, the member- access modifiers declare our instance variables public void setTime( int h, int m, int s ) { private. hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); When this ( ( m >= 0 && m < 60 ) ? m the only way minute = class gets instantiated, : 0 ); to access = ( ( svariables is through :the); second these >= 0 && s < 60 ) ? s 0 methods } of the class. http://www.java2all.com
  • 14. import java.text.DecimalFormat; public class Time1 extends Object { The Constructor private int hour; // 0 - 23 method “ Time1()” private int minute; // 0 - 59 private int second; // 0 - 59 must have the same name as the class so public Time1() { the compiler always setTime( 0, 0, 0 ); knows how to } initialize the class. public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } http://www.java2all.com
  • 15. import java.text.DecimalFormat;in The method setTime()takes the time arguments. It validates the Time1 extends Objectseconds to make sure they public class hours, minutes and make sense. Now you can see why the concept of a class { private int hour; // 0 - 23 might be prettyminute; // 0 - 59 private int nifty. private int second; // 0 - 59 public Time1() { setTime( 0, 0, 0 ); } public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } http://www.java2all.com
  • 16. Using Our New Class • We cannot instantiate it in this class. • We need to create another class to do actually make an example of this class. http://www.java2all.com
  • 17. Using Our New Class • We need to create a driver program TimeTest.java • The only purpose of this new class is to instantiate and test our new class Time1. http://www.java2all.com
  • 18. Introduction To Method http://www.java2all.com
  • 19. As we all know that, classes usually consist of two things instance variables and methods. • Here we are going to explain some fundamentals about methods. • So we can begin to add methods to our classes. • Methods are defined as follows • § Return type • § Name of the method • § A list of parameters • § Body of the method. http://www.java2all.com
  • 20. Syntax: return type method name (list of parameters) { Body of the method } • return type specifies the type of data returned by the method. This can be any valid data type including class types that you create. • If the method does not return a value, its return type must be void, Means you can say that void means no return. http://www.java2all.com
  • 21. • Methods that have a return type other than void return a value to the calling routine using the following form of the return statement: • return value; Here, value is the value returned. • The method name is any legal identifier. • The list of parameter is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. • If the method has no parameters, then the parameter list will be empty. http://www.java2all.com
  • 22. import java.util.Scanner; class Box { double width; double height; double depth; void volume() // display volume of a box { System.out.print("Volume is : "); System.out.println(width * height * depth); } } class BoxDemo { public static void main(String args[]) { Box box1 = new Box(); // defining object box1 of class Box Scanner s = new Scanner(System.in); System.out.print(“Enter Box Width : ”); box1.width = s.nextDouble(); System.out.print(“Enter Box Height : ”); box1.height = s.nextDouble(); System.out.print(“Enter Box Depth : ”); box1.depth = s.nextDouble(); // display volume of box1 box1.volume(); // calling the method volume } } http://www.java2all.com
  • 23. Constructors http://www.java2all.com
  • 24. Constructors • The Constructor is named exactly the same as the class. • The Constructor is called when the new keyword is used. • The Constructor cannot have any return type — not even void. http://www.java2all.com
  • 25. Constructors • The Constructor instantiates the object. • It initializes instance variables to acceptable values. • The “default” Constructor accepts no arguments. • The Constructor method is usually overloaded. http://www.java2all.com
  • 26. Varieties of Methods: Constructors • The overloaded Constructor usually takes arguments. • That allows the class to be instantiated in a variety of ways. • If the designer neglects to include a constructor, then the compiler creates a default constructor that takes no arguments. • A default constructor will call the Constructor for the class this one extends. http://www.java2all.com
  • 27. public Time2() { setTime( 0, 0, 0 ); } • This is the first Constructor. • Notice that it takes no arguments, but it still sets the instance variables for hour, minute and second to consistent initial values of zero. http://www.java2all.com
  • 28. public Time2() { setTime( 0, 0, 0 ); } public Time2( int h, int m, int s ) { setTime( h, m, s ); } • These are the first two Constructors. • The second one overrides the first. • The second Constructor takes arguments. • It still calls the setTime() method so it can validate the data. http://www.java2all.com
  • 29. public Time2() { setTime( 0, 0, 0 ); } Usually, we can’t directly access the private instance variables of an public Time2( int h, int m, int s ) { object, because it violates setTime( h, m, encapsulation. s ); } However, objects of the same class are public Time2( Time2 time access each other’s permitted to ) { instance variables directly. setTime( time.hour, time.minute, time.second ); } • This final constructor is quite interesting. • It takes as an argument a Time2 object. • This will make the two Time2 objects equal. http://www.java2all.com
  • 30. public class Employee extends Object { private String firstName; private String lastName; private static int count; // # of objects in memory public Employee( String fName, String lName ) { firstName = fName; lastName = lName; ++count; // increment static count of employees System.out.println( "Employee object constructor: " + firstName + " " + lastName ); } protected void finalize() Because count is declared as private static, the { —count; // decrement static count of employees System.out.println( "Employee object finalizer: " + firstName + " " + to access + only way lastName its data "; count = "by count ); public is + using a } static method. public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public static int getCount() { return count; } } http://www.java2all.com
  • 31. public class Employee extends Object { private String firstName; private String lastName; private static int count; // # of objects in memory public Employee( String fName, String lName ) { firstName = fName; lastName = lName; ++count; // increment static count of employees System.out.println( "Employee object constructor: " + firstName + " " + lastName ); } protected void finalize() { —count; // decrement static count of employees System.out.println( "Employee object finalizer: " + firstName + " " + lastName + "; count = " + count ); } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public static int getCount() { return count; } } http://www.java2all.com
  • 32. Access Modifiers http://www.java2all.com
  • 33. Superclasses and Subclasses Impact on Access Modifiers • Access Modifiers are among the thorniest and most confusing aspects of OOP. • But, remember, encapsulation is one of the primary benefits of object orientation, so access is important. http://www.java2all.com
  • 34. Superclasses and Subclasses Impact on Access Modifiers • The familiar private access modifier lets us shield our instance variables from the prying eyes of the outside world. • Relying on Access Modifiers, you can shield both your class’s private instance variables and its private methods. http://www.java2all.com
  • 35. Superclasses and Subclasses Impact on Access Modifiers • With those ends in mind, Java lets review the four different levels of access: private, protected, public and the default if you don’t specify package. http://www.java2all.com
  • 36. Superclasses and Subclasses • A summary of the various types of access modifier: Specifier class subclass package world private X package X X protected X X X public X X X X http://www.java2all.com
  • 37. Superclasses and Subclasses • As you can see, a class always has access to its own instance variables, with any access modifier. Specifier class subclass package world private X package X X protected X X X public X X X X http://www.java2all.com
  • 38. Superclasses and Subclasses • The second column shows that Subclasses of this class (no matter what package they are in) have access to public (obviously) and protected variables. Specifier class subclass package world private X package X X protected X X X public X X X X http://www.java2all.com
  • 39. • Therefore, the important point? Subclasses can reach protected-access variables, but can’t reach package-access variables… unless the Subclasses happen to be saved in the same package. http://www.java2all.com
  • 40. Superclasses and Subclasses • The third column “package” shows that classes in the same package as the class (regardless of their parentage) have access to data variables. Specifier class subclass package world private X package X X protected X X X public X X X X http://www.java2all.com
  • 41. Superclasses and Subclasses • In the fourth column, we see that anything and anyone has access to a public data variable or method—defeating the purpose of encapsulation. Specifier class subclass package world private X package X X protected X X X public X X X X http://www.java2all.com
  • 42. private http://www.java2all.com
  • 43. Superclasses and Subclasses Impact on Access Modifiers: private • When my class inherits from a Superclass, I cannot access the Superclass’s private data variables. Private data is Secret! • In other words, the Subclass cannot automatically reach the private data variables of the Superclass. • A private data variable is accessible only to the class in which it is defined. http://www.java2all.com
  • 44. Objects of type Alpha can inspect or modify the iamprivate variable and can call privateMethod, but objects of any other type cannot. class Alpha { private int iamprivate; public Alpha( int iam ) { iamprivate = iam; } private void privateMethod() { iamprivate = 2; System.out.println(“” + iamprivate); } } http://www.java2all.com
  • 45. The Beta class, for example, cannot access the iamprivate variable or invoke privateMethod on an object of type Alpha because Beta is not of type Alpha . class Beta { public void accessMethod() { Alpha a = new Alpha(); a.iamprivate = 10; // Invalid a.privateMethod(); // Invalid } } • The compiler would complain if you tried this. http://www.java2all.com
  • 46. Can one instance of an Alpha object access the private data variables of another instance of an Alpha object? Yes! Objects of the same type have access to one another’s private members. http://www.java2all.com
  • 47. package http://www.java2all.com
  • 48. Superclasses and Subclasses Varieties of Access Modifiers: package • If you do not specify the access for either a method or an encapsulated data variable, then it is given the default access: package http://www.java2all.com
  • 49. Superclasses and Subclasses Varieties of Access Modifiers: package • This access allows other classes in the same package as your class to access its data variables as if they were their own. package • This level of access assumes that classes in the same package as your class are friends who won’t harm your class’ data. http://www.java2all.com
  • 50. • Notice that no access modifier is declared. So, iamprivate and method privateMethod both default to package access. • All classes declared in the package Greek, along with class Delta, have access to iamprivate and privateMethod. package Greek; class Delta { int iamprivate; void privateMethod() { System.out.println(“privateMethod”); } }
  • 51. Superclasses and Subclasses Varieties of Access Modifiers: package package • If you use multiple objects from the same package, they can access each other’s package- access methods and data variables directly, merely by referencing an object that has been instantiated. http://www.java2all.com
  • 52. Superclasses and Subclasses Varieties of Access Modifiers: package package • With package access, other objects in the package don’t have to bother going through the methods. They can get right to the variables. http://www.java2all.com
  • 53. Superclasses and Subclasses • So, when you don’t include any access modifier, you are in fact giving your variable package access. int x; // package access instance variable • Notice, it’s declared neither public nor private. http://www.java2all.com
  • 54. protected http://www.java2all.com
  • 55. Superclasses and Subclasses • protected allows the class itself, Subclasses and all classes in the same package to access the members. • Generally speaking, protected offers greater access than package access. http://www.java2all.com
  • 56. Superclasses and Subclasses • Use the protected access level when it’s appropriate for a class’s Subclasses to have access to the member, but not for unrelated classes to have access. • protected members are like family secrets— you don’t mind if someone in the family knows— but you don’t want outsiders to know. http://www.java2all.com
  • 57. Superclasses and Subclasses • The Access Modifier protected can be used on either a method or an encapsulated data variable. • protected serves as a middle ground between the private and public access modifier. http://www.java2all.com
  • 58. Superclasses and Subclasses • A Superclass’s protected data variables may be accessed only by: —methods of the Superclass —methods of the Subclass —methods of other classes in the same package. Or we can summarize: protected members have package access. http://www.java2all.com

Notas do Editor

  1. White Space Characters
  2. White Space Characters
  3. White Space Characters
  4. White Space Characters
  5. White Space Characters
  6. White Space Characters
  7. White Space Characters
  8. White Space Characters
  9. White Space Characters
  10. White Space Characters
  11. White Space Characters