SlideShare a Scribd company logo
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

More Related Content

PPTX
Nanochemistry
Thakur Sandilya
 
PPTX
Java
Tony Nguyen
 
PDF
Python Flow Control
Mohammed Sikander
 
PPTX
Presentation on Core java
mahir jain
 
PPTX
Data Modeling PPT
Trinath
 
PDF
JAVA PPT Part-1 BY ADI.pdf
Prof. Dr. K. Adisesha
 
PPTX
Liquid Crystal Display (LCD)
Bhaskar Jyoti Sarma
 
PPSX
Elements of Java Language
Hitesh-Java
 
Nanochemistry
Thakur Sandilya
 
Python Flow Control
Mohammed Sikander
 
Presentation on Core java
mahir jain
 
Data Modeling PPT
Trinath
 
JAVA PPT Part-1 BY ADI.pdf
Prof. Dr. K. Adisesha
 
Liquid Crystal Display (LCD)
Bhaskar Jyoti Sarma
 
Elements of Java Language
Hitesh-Java
 

What's hot (20)

PPTX
Strings in Java
Abhilash Nair
 
PPTX
Java abstract class & abstract methods
Shubham Dwivedi
 
PPTX
This keyword in java
Hitesh Kumar
 
PPTX
Method overloading
Lovely Professional University
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PPTX
Constructor in java
SIVASHANKARIRAJAN
 
PPTX
INHERITANCE IN JAVA.pptx
NITHISG1
 
PPTX
MULTI THREADING IN JAVA
VINOTH R
 
PDF
Java I/o streams
Hamid Ghorbani
 
PPTX
Inheritance in java
RahulAnanda1
 
PPTX
Constructor in java
Pavith Gunasekara
 
PPTX
Java exception handling
BHUVIJAYAVELU
 
PPT
Java Streams
M Vishnuvardhan Reddy
 
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
PPT
Collection Framework in java
CPD INDIA
 
PPS
Interface
kamal kotecha
 
PDF
Methods in Java
Jussi Pohjolainen
 
PPT
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
PPS
Wrapper class
kamal kotecha
 
PPTX
Functions in python
colorsof
 
Strings in Java
Abhilash Nair
 
Java abstract class & abstract methods
Shubham Dwivedi
 
This keyword in java
Hitesh Kumar
 
Method overloading
Lovely Professional University
 
Classes, objects in JAVA
Abhilash Nair
 
Constructor in java
SIVASHANKARIRAJAN
 
INHERITANCE IN JAVA.pptx
NITHISG1
 
MULTI THREADING IN JAVA
VINOTH R
 
Java I/o streams
Hamid Ghorbani
 
Inheritance in java
RahulAnanda1
 
Constructor in java
Pavith Gunasekara
 
Java exception handling
BHUVIJAYAVELU
 
Java Streams
M Vishnuvardhan Reddy
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
Collection Framework in java
CPD INDIA
 
Interface
kamal kotecha
 
Methods in Java
Jussi Pohjolainen
 
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
Wrapper class
kamal kotecha
 
Functions in python
colorsof
 
Ad

Similar to Introduction to class in java (20)

PPT
oops-1
snehaarao19
 
PPT
Unit i
snehaarao19
 
PDF
OOPs & Inheritance Notes
Shalabh Chaudhary
 
PPT
Class & Objects in JAVA.ppt
RohitPaul71
 
PDF
ádfasdfasdfasdfasdfasdfsadfsadfasdfasfasdfasdfasdfa
Vu Dang
 
PPS
Packages and inbuilt classes of java
kamal kotecha
 
PDF
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
DOCX
Java sessionnotes
Lakshmi Sarvani Videla
 
PPT
Defining classes-and-objects-1.0
BG Java EE Course
 
PPTX
Closer look at classes
yugandhar vadlamudi
 
PPTX
object oriented programming using java, second sem BCA,UoM
ambikavenkatesh2
 
PPT
9781439035665 ppt ch08
Terry Yoast
 
PPTX
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
PPT
Chap08
Terry Yoast
 
PPTX
Computer programming 2 Lesson 15
MLG College of Learning, Inc
 
PPT
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
PPTX
Object oriented design
lykado0dles
 
PPTX
C# classes objects
Dr.Neeraj Kumar Pandey
 
PPTX
introduction to object oriented programming language java
RitikGarg39
 
PPTX
Core java oop
Parth Shah
 
oops-1
snehaarao19
 
Unit i
snehaarao19
 
OOPs & Inheritance Notes
Shalabh Chaudhary
 
Class & Objects in JAVA.ppt
RohitPaul71
 
ádfasdfasdfasdfasdfasdfsadfsadfasdfasfasdfasdfasdfa
Vu Dang
 
Packages and inbuilt classes of java
kamal kotecha
 
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Java sessionnotes
Lakshmi Sarvani Videla
 
Defining classes-and-objects-1.0
BG Java EE Course
 
Closer look at classes
yugandhar vadlamudi
 
object oriented programming using java, second sem BCA,UoM
ambikavenkatesh2
 
9781439035665 ppt ch08
Terry Yoast
 
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
Chap08
Terry Yoast
 
Computer programming 2 Lesson 15
MLG College of Learning, Inc
 
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
Object oriented design
lykado0dles
 
C# classes objects
Dr.Neeraj Kumar Pandey
 
introduction to object oriented programming language java
RitikGarg39
 
Core java oop
Parth Shah
 
Ad

More from kamal kotecha (18)

PPS
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
PPTX
Network programming in java - PPT
kamal kotecha
 
PPT
Java servlet life cycle - methods ppt
kamal kotecha
 
PPS
Java rmi example program with code
kamal kotecha
 
PPS
Java rmi
kamal kotecha
 
PPS
Jdbc example program with access and MySql
kamal kotecha
 
PPS
Jdbc api
kamal kotecha
 
PPS
Jdbc architecture and driver types ppt
kamal kotecha
 
PPS
Java Exception handling
kamal kotecha
 
PPS
JSP Error handling
kamal kotecha
 
PPS
Jsp element
kamal kotecha
 
PPS
Jsp chapter 1
kamal kotecha
 
PPS
String and string buffer
kamal kotecha
 
PPS
Inheritance chepter 7
kamal kotecha
 
PPS
Class method
kamal kotecha
 
PPS
Control statements
kamal kotecha
 
PPTX
Jsp myeclipse
kamal kotecha
 
PPTX
basic core java up to operator
kamal kotecha
 
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
Network programming in java - PPT
kamal kotecha
 
Java servlet life cycle - methods ppt
kamal kotecha
 
Java rmi example program with code
kamal kotecha
 
Java rmi
kamal kotecha
 
Jdbc example program with access and MySql
kamal kotecha
 
Jdbc api
kamal kotecha
 
Jdbc architecture and driver types ppt
kamal kotecha
 
Java Exception handling
kamal kotecha
 
JSP Error handling
kamal kotecha
 
Jsp element
kamal kotecha
 
Jsp chapter 1
kamal kotecha
 
String and string buffer
kamal kotecha
 
Inheritance chepter 7
kamal kotecha
 
Class method
kamal kotecha
 
Control statements
kamal kotecha
 
Jsp myeclipse
kamal kotecha
 
basic core java up to operator
kamal kotecha
 

Recently uploaded (20)

PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
PPTX
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
Introduction and Scope of Bichemistry.pptx
shantiyogi
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PPT
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PPTX
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
PPTX
How to Manage Global Discount in Odoo 18 POS
Celine George
 
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
Sourav Kr Podder
 
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PPTX
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
Introduction and Scope of Bichemistry.pptx
shantiyogi
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
How to Manage Global Discount in Odoo 18 POS
Celine George
 
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
Open Quiz Monsoon Mind Game Final Set.pptx
Sourav Kr Podder
 
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 

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

Editor's Notes

  • #34: White Space Characters
  • #35: White Space Characters
  • #36: White Space Characters
  • #44: White Space Characters
  • #49: White Space Characters
  • #50: White Space Characters
  • #52: White Space Characters
  • #53: White Space Characters
  • #54: White Space Characters
  • #58: White Space Characters
  • #59: White Space Characters