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
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
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
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
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
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
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