0% found this document useful (0 votes)
12 views

OOP in Java - Part 2

The document discusses Java methods that can accept a variable number of arguments. It explains that the variable arguments must always be the last parameter declared in the method signature. It also shows how vararg methods can be overloaded based on the type of the vararg parameter.

Uploaded by

gourilakshmis78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

OOP in Java - Part 2

The document discusses Java methods that can accept a variable number of arguments. It explains that the variable arguments must always be the last parameter declared in the method signature. It also shows how vararg methods can be overloaded based on the type of the vararg parameter.

Uploaded by

gourilakshmis78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

OOP through Java

static keyword

 to define a class member that will be used independently of any object of that
class
 When a member is declared static, it can be accessed before any objects of its
class are created, and without reference to any object.
 can declare both methods and variables to be static
 Instance variables declared as static are, essentially, global variables.
 When objects of its class are declared, no copy of a static variable is made.
Instead, all instances of the class share the same static variable.
 Methods declared as static have several restrictions:
 They can only directly call other static methods of their class.
 They can only directly access static variables of their class.
 They cannot refer to this or super in any way.
 if you wish to call a static method from outside its class, you can do so using
the following general form:
classname.method( )
2
static keyword

3
final keyword

 A field can be declared as final to prevents its contents from being modified,
making it, essentially, a constant
 You can do this in one of two ways:
 First, you can give it a value when it is declared.
 Second, you can assign it a value within a constructor.
 The first approach is probably the most common.
 Here is an example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
 In addition to fields, both method parameters and local variables can be
declared final.
 Declaring a parameter final prevents it from being changed within the method.
 Declaring a local variable final prevents it from being assigned a value more
than once
 final can also be applied to methods, and is explained when inheritance is
discussed. 4
Introducing Access Control

 encapsulation provides another important attribute: access


control.
 Through encapsulation, you can control what parts of a program
can access the members of a class.
 By controlling access, you can prevent misuse.
 How a member can be accessed is determined by the access
modifier attached to its declaration.
 Some aspects of access control are related mostly to inheritance
or packages. (A package is, essentially, a grouping of classes.)
 Java’s access modifiers are public, private, and protected.
 Java also defines a default access level.
 protected applies only when inheritance is involved.
5
Introducing Access Control

 In the classes developed so far, all members of a class have used


the default access mode.
 Sometimes we want to restrict access to the data members of a
class— allowing access only through methods.
 Also, there will be times when you will want to define methods
that are private to a class.
 An access modifier precedes the rest of a member’s type
specification - is, it must begin a member’s declaration statement.
public int i;
private double j;
private int myMethod(int a, char b) { //...

6
7
Nested and Inner Classes

 It is possible to define a class within another class; such classes are known as
nested classes
 The scope of a nested class is bounded by the scope of its enclosing class
 Thus, if class B is defined within class A, then B does not exist independently
of A
 A nested class has access to the members, including private members, of the
class in which it is nested
 However, the enclosing class does not have access to the members of the
nested class
 A nested class that is declared directly within its enclosing class scope is a
member of its enclosing class

8
Nested and Inner Classes

 There are two types of nested classes: static and non-static


 A static nested class is one that has the static modifier applied
 Because it is static, it must access the non-static members of its enclosing class
through an object - it cannot refer to non-static members of its enclosing class
directly
 Because of this restriction, static nested classes are seldom used.
 The most important type of nested class is the inner class
 An inner class is a non-static nested class
 It has access to all of the variables and methods of its outer class and may refer
to them directly in the same way that other non-static members of the outer
class do.
 It is also possible to declare a nested class that is local to a block.

9
inner classes within any block scope

 nested classes are not applicable to all situations, they are


particularly helpful when handling events 10
Exploring the String Class

 String is probably the most commonly used class in Java’s class library
 The obvious reason for this is that strings are a very important part of
programming
 The first thing to understand about strings is that every string you create is
actually an object of type String
 Even string constants are actually String objects
 For example, in the statement
System.out.println("This is a String, too");
 the string "This is a String, too" is a String object
 The second thing to understand about strings is that objects of type String are
immutable; once a String object is created, its contents cannot be altered
 While this may seem like a serious restriction, it is not, for two reasons:
 If you need to change a string, you can always create a new one that contains the
modifications
 Java defines peer classes of String, called StringBuffer and StringBuilder, which allow
strings to be altered, so all of the normal string manipulations are still available in Java
11
Exploring the String Class

 Strings can be constructed in a variety of ways


 The easiest is to use a statement like this:
String myString = "this is a test";
 Once you have created a String object, you can use it anywhere that a string is
allowed
 For example, this statement displays myString:
System.out.println(myString);
 Java defines one operator for String objects: +
 It is used to concatenate two strings
 For example, this statement
String myString = "I" + " like " + "Java";
 results in myString containing "I like Java"

12
Methods of String class

 The String class contains several methods.


 You can test two strings for equality by using equals( ).
 You can obtain the length of a string by calling the length( )
method.
 You can obtain the character at a specified index within a string
by calling charAt( ).
 The general forms of these three methods are shown here:
 boolean equals(secondStr)
 int length( )
 char charAt(index)

13
Command-Line Arguments

14
Varargs: Variable-Length Arguments
 A method that takes a variable number of arguments is called a variable-arity
method, or simply a varargs method.
 Beginning with JDK 5, Java has included this feature

15
Varargs: Variable-Length Arguments

 A method can have “normal” parameters along with a variable-length


parameter.
 However, the variable-length parameter must be the last parameter declared by
the method.
 For example, this method declaration is perfectly acceptable:
int doIt(int a, int b, double c, int ... vals) {
 In this case, the first three arguments used in a call to doIt( ) are matched to the first
three parameters.
 Then, any remaining arguments are assumed to belong to vals.
 Remember, the varargs parameter must be last.
 For example, the following declaration is incorrect:
int doIt(int a, int b, double c, int ... vals, boolean stopFlag) { // Error!
 there must be only one varargs parameter.
 For example, this declaration is also invalid:
 int doIt(int a, int b, double c, int ... vals, double ... morevals) { //
Error!
16
Overloading Vararg Methods
//Varargs and overloading.
class VarArgs3
{
static void vaTest(int ... v)
{
System.out.print("vaTest(int ... ): "+ "Number of args: " + v. length + "Contents: ");
for(int x : v)
System. out. print (x + " ") ;
System.out.println();
}
static void vaTest(boolean ... v)
{
System.out.print("vaTest(boolean ... ) " + "Number of args: " + v. length + "Contents: ");
for(boolean x : v)
System. out. print (x + " ") ;
System.out.println();
}
static void vaTest(String msg, int ... v)
{
System.out.print("vaTest(String, int ... ):"+ msg + v.length + "Contents: ");
for ( int x : v)
System. out. print (x + " ") ;
System.out.println();
}
public static void main(String args[])
{
vaTest(1, 2, 3);
vaTest ("Testing: ", 10, 20);
vaTest(true, false, false);
}
}

17
18
Type Inference with Local Variables
 Recently, an exciting new feature called local variable type inference was added to the
Java language.
 Beginning with JDK 10, it is now possible to let the compiler infer the type of a local
variable based on the type of its initializer, thus avoiding the need to explicitly specify
the type
 local variable type inference has become a common part of the contemporary
programming environment
 type inference, the context-sensitive identifier var was added
 var counter; // Wrong! Initializer required.
 var avg = 10.0;
 int var = 1; // In this case, var is simply a user-defined identifier.
 var myArray = new int[10]; // This is valid.
 var[] myArray = new int[10]; // Wrong
 var myArray[] = new int[10]; // Wrong
 var myArray = { 1, 2, 3 }; // Wrong
 Only one variable can be declared at a time;
 a variable cannot use null as an initializer; and the variable being declared
 cannot be used by the initializer expression
19
Local Variable Type Inference with
Reference Types

 Earlier examples have shown type inference with primitive types, but it can
also be used with reference types.
var myStr = "This is a string";
 one of the benefits of local variable type inference is its ability to streamline
code, and it is with reference types where such streamlining is most apparent.
 The reason for this is that many class types in Java have rather long names.
FileInputStream fin = new FileInputStream("test.txt");
 With the use of var, it can now be written like this:
var fin = new FileInputStream("test.txt");

20
Local Variable Type Inference with
Reference Types

21
Inheritance
 Inheritance is one of the cornerstones of object-oriented programming because
it allows the creation of hierarchical classifications.
 Using inheritance, you can create a general class that defines traits common to
a set of related items.
 This class can then be inherited by other, more specific classes, each adding
those things that are unique to it.
 In the terminology of Java, a class that is inherited is called a superclass.
 The class that does the inheriting is called a subclass.
 Therefore, a subclass is a specialized version of a superclass.
 It inherits all of the members defined by the superclass and adds its own,
unique elements.
 To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword
 The general form of a class declaration that inherits a superclass:
 class subclass-name extends superclass-name {
 // body of class
22
Inheritance

23
Inheritance

24
Member Access and Inheritance

25
Member Access and Inheritance

26
Member Access and Inheritance

 Box revisited
 ColorBox

27
A Superclass Variable Can
Reference a Subclass Object

 A reference variable of a superclass can be assigned a reference to any


subclass derived from that superclass.

28
super keyword

 when a superclass keeps the details of its implementation to itself (that is, that
keeps its data members private).
 In this case, there would be no way for a subclass to directly access or
initialize these variables on its own.
 Whenever a subclass needs to refer to its immediate superclass, it can do so by
use of the keyword super
 super has two general forms. The first calls the superclass’ constructor.
 The second is used to access a member of the superclass that has been hidden
by a member of a subclass.

29
super to Call Superclass Constructors

 A subclass can call a constructor defined by its superclass by use of the


following form of super:
super(arg-list);
 Here, arg-list specifies any arguments needed by the constructor in the
superclass.
 super( ) must always be the first statement executed inside a subclass’
constructor.
 To see how super( ) is used, consider this improved version of the BoxWeight
class:

30
31
32
33
34
A Second Use for super

 The second form of super acts somewhat like this, except that it always refers
to the superclass of the subclass in which it is used.
super.member
 This second form of super is most applicable to situations in which member
names of a subclass hide members by the same name in the superclass.

35
36
Creating a Multilevel Hierarchy

37
Creating a Multilevel Hierarchy

38
Creating a Multilevel Hierarchy

39
Creating a Multilevel Hierarchy

40
Constructor invocation in
Multilevel Hierarchy
 In a class hierarchy,
constructors complete
their execution in order of
derivation, from
superclass to subclass.
 As, since super( ) must be
the first statement
executed in a subclass’
constructor, this order is
the same whether or not
super( ) is used.
 If super( ) is not used,
then the default or
parameter-less
constructor of each
superclass will be
executed
41
Method Overriding

 In a class hierarchy, when a method in a subclass has the same name and
type signature as a method in its superclass, then the method in the subclass
is said to override the method in the superclass.
 When an overridden method is called from within its subclass, it will always
refer to the version of that method defined by the subclass.
 The version of the method defined by the superclass will be hidden.

42
Method Overriding

 If you wish to access the superclass version of an overridden method, you can
do so by using super.
43
Overriding vs Overloading
 Method overriding occurs
only when the names and
the type signatures of the
two methods are identical.
 If they are not, then the two
methods are simply
overloaded.

44
Dynamic Method Dispatch

 Method overriding forms the basis for one of Java’s most powerful concepts:
dynamic method dispatch.
 Dynamic method dispatch is the mechanism by which a call to an overridden
method is resolved at run time, rather than compile time.
 Dynamic method dispatch is important because this is how Java implements
run-time polymorphism.
 Java uses the fact “a superclass reference variable can refer to a subclass
object” to resolve calls to overridden methods at run time.
 When an overridden method is called through a superclass reference, Java
determines which version of that method to execute based upon the type of the
object being referred to at the time the call occurs (at run time).
 it is the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be
executed.

45
Dynamic Method Dispatch

46
Dynamic Method Dispatch – Ex2

47
Applying Method Overriding

48
Applying Method Overriding

49
Abstract Classes

 sometimes you will want to create a superclass that only defines a generalized
form that will be shared by all of its subclasses, leaving it to each subclass to
fill in the details.
 Such a class determines the nature of the methods that the subclasses must
implement.
 One way this situation can occur is when a superclass is unable to create a
meaningful implementation for a method.
 The definition of area( ) is simply a placeholder. It will not compute and
display the area of any type of object.
 As you will see as you create your own class libraries, it is not uncommon for
a method to have no meaningful definition in the context of its superclass.
 You can handle this situation two ways.
 Consider the class Triangle. It has no meaning if area( ) is not defined. In this
case, you want some way to ensure that a subclass does, indeed, override all
necessary methods. Java’s solution to this problem is the abstract method.
50
Abstract Classes

 certain methods be overridden by subclasses by specifying the abstract type


modifier.
 These methods are sometimes referred to as subclasser responsibility because
they have no implementation specified in the superclass.
 Thus, a subclass must override them—it cannot simply use the version defined
in the superclass.
 To declare an abstract method, use this general form:
abstract type name(parameter-list);
 Any class that contains one or more abstract methods must also be declared
abstract.
 There can be no objects of an abstract class.
 Also, you cannot declare abstract constructors, or abstract static methods.
 Any subclass of an abstract class must either implement all of the abstract
methods in the superclass, or be declared abstract itself.

51
Abstract Classes

52
Abstract Classes

 Although abstract classes cannot be used to instantiate objects, they can be


used to create object references, because Java’s approach to run-time
polymorphism is implemented through the use of superclass references.
 Thus, it must be possible to create a reference to an abstract class so that it can
be used to point to a subclass object.

53
54
final with Inheritance

 Using final to Prevent Overriding

55
final with Inheritance

 Methods declared as final can sometimes provide a performance enhancement:


The compiler is free to inline calls to them because it “knows” they will not be
overridden by a subclass.
 When a small final method is called, often the Java compiler can copy the
bytecode for the subroutine directly inline with the compiled code of the
calling method, thus eliminating the costly overhead associated with a method
call.
 Inlining is an option only with final methods.
 Normally, Java resolves calls to methods dynamically, at run time. This is
called late binding.
 since final methods cannot be overridden, a call to one can be resolved at
compile time. This is called early binding.

56
final to Prevent Inheritance

 Sometimes you will want to prevent a class from being inherited.


 To do this, precede the class declaration with final.
 Declaring a class as final implicitly declares all of its methods as final, too.
 As you might expect, it is illegal to declare a class as both abstract and final

57
Local Variable Type Inference and
Inheritance

 local variable type inference which is supported by the reserved type name var
type of a variable is based on the declared type of its initializer
 Recall that a superclass reference can refer to a derived class object, and this
feature is part of Java’s support for polymorphism
 If the initializer is of the superclass type, that will be the inferred type of the
variable.
 It does not matter if the actual object being referred to by the initializer is an
instance of a derived class

58
Local Variable Type Inference and
Inheritance

59
Local Variable Type Inference and
Inheritance

60
The Object Class

 There is one special class, Object, defined by Java.


 All other classes are subclasses of Object. That is, Object is a superclass of all
other classes.
 This means that a reference variable of type Object can refer to an object of
any other class.
 Also, since arrays are implemented as classes, a variable of type Object can
also refer to any array.

61
The Object Class

 Object defines the following methods, which means that they are available in
every object.

62

You might also like