This document provides an overview of key concepts in Java including classes, objects, class members, packages, constructors, interfaces, abstract classes, object-oriented programming characteristics like encapsulation, inheritance, polymorphism and abstraction. It also discusses overriding, overloading, non-access modifiers, passing variables and strings. The presentation contains definitions and examples to explain each concept in 1-3 sentences.
7. Classes & Objects
● Object-Oriented Programming is a methodology or
paradigm to design a program using classes and objects.
● Object - any entity that has state and behavior is known as
an object.
● Class - a class is the blueprint from which objects are created.
8. Classes & Objects
When you design a class, think about the objects that will be created from
that class type.
Think about:
● Things the object knows (instance variables)
● Things the object does (methods)
9. Class Definition
In general, class declarations can include these
components, in order:
1. Access Modifiers such as public, private,....
2. The Class Name.
3. The name of the class's parent (superclass), if any,
preceded by the keyword extends.
4. A comma-separated list of interfaces implemented
by the class, if any, preceded by the keyword
implements.
5. The class body, surrounded by braces, {}.
Access Modifier Class Name
Instance Variables
Methods
11. Access Modifiers
Access modifiers define the scope of variables, methods, constructors or
classes,...
● public: Visible to the world.
● protected: Visible to the package & all subclasses.
● default (no modifiers): Visible to the package
● private: Visible to the class only
12. Class Members: Instance Variables
● Instance Variables = Class Attributes = Class Variables = Data Members =
Properties
● Instance variables are defined inside the class, but outside of any method,
and are only initialized when the class is instantiated.
● Instance variables are the fields that belong to each unique object.
13. Class Members: Instance Variables
● You must declare all variables before they can be used.
● Following is the basic form of a variable declaration:
modifiers data-type variable-name [ = value][, variable [ = value] ...] ;
14. Class Members: Instance Variables
● It's not always necessary to assign a
value when a instance variable is
declared.
● Instance variables that are declared but
not initialized will be set to a reasonable
default by the compiler.
● Generally speaking, this default will be
zero or null, depending on the data
type.
15. Class Members: Methods
A Java method is a collection of statements that are grouped together to
perform an operation.
16. Class Members: Methods
Syntax:
modifiers return-type method-name([parameters]) [throws exception-list] {
// Method Body
}
● Modifiers: optional - defines the access type of the method
● Return type: required - a data type or void
● Method name: required - used to call method from somewhere
● () - required, but parameter list is optional
● Exception list - Optional
● { Body } - required for non-abstract method.
18. Package
● A package is a namespace that organizes a set of related classes,
interfaces, enums or annotations.
● Conceptually you can think of packages as being similar to different
folders on your computer.
● Packages are used in Java in order to:
○ Provide namespace management (prevent naming conflicts)
○ Provide access protection.
○ Make searching/locating and usage of classes easier.
19. “import” keyword
● If a class wants to use another class in the same package, the package
name need not be used.
● If a class wants to use another class in another package, it must use one
of 3 techniques:
○ Use fully qualified name of the class it want to use.
○ The package can be imported using “import” keyword and the wild card (*).
○ The class itself can be imported using “import” keyword.
21. Constructors
● Constructor is a special type of method that is used to initialize the object.
● Every class, including abstract classes, MUST have a constructor.
● Every time you make a new object, at least one constructor is invoked.
● Use “new” keyword to initialize an object (automatic call a constructor).
22. Constructors
Declaration rules:
● Constructors must have the same name as the class in which they are
declared.
● Constructors must NOT have a return type.
● Constructors can’t be marked “static”, “abstract” or “final”.
● Constructors could have parameters or not.
23. Constructors
Declaration rules (cont.):
● If you don't type a constructor into your class code, a default
constructor will be automatically generated by the compiler.
● The default constructor is ALWAYS a no-arg constructor.
● If you declare any constructor(s) into your class, the compiler won’t
provide the default constructor for you.
24. Constructors Chaining
Horse h = new Horse();
(assume Horse extends Animal and Animal extends Object.)
Question: Which constructor(s) are invoked, in which order?
26. Abstract Methods
An abstract method is a method that is declared without an implementation.
access-modifiers abstract return-type method-name([parameters]);
27. Interfaces
● An interface is a reference type, similar to a class, that can contain only
constants and method signatures (Abstract Methods).
access-modifiers interface interface-name([parameters]) [throws exception-list] {
// Interface body: Constants & Abstract Methods
}
● A class implementing an interface must provide implementation for all of
its method unless it’s an abstract class.
31. Abstract Class
● An abstract class is a class that is declared abstract—it may or may not
include abstract methods.
● Abstract classes cannot be instantiated, but they can be subclassed.
● If a class includes abstract methods, then the class itself must be declared
abstract.
● If a class is declared abstract, it can NOT be instantiated.
35. Encapsulation
How do you do that?
● Keep instance variables protected (with an access modifier, often private).
● Make public accessor methods, and force calling code to use those methods
(rather than directly accessing the instance variable).
● For the methods, use the JavaBeans naming convention of
set<someProperty> and get<someProperty>.
39. Inheritance
● Use 2 keywords: extends and
implements.
● Inherited resources depends on the
access modifiers.
● All Java classes inherit the Object class.
● A class extends an abstract class or
implements an interface, must
override all the abstract methods.
42. Polymorphism
● Any Java object that can pass more than one IS-A test is considered to be
polymorphic.
● The only possible way to access an object is through a reference
variable.
43. Polymorphism
● A reference variable can be of only one type.
● A reference is a variable, so it can be reassigned to other objects.
● The type of the reference variable would determine the methods that it
can invoke on the object.
● A reference variable can refer to any object of its declared type or any
subtype of its declared type.
● A reference variable can be declared as a class or interface type.
46. Abstraction
● Achieved by using abstract classes or interfaces.
● All subclass must implement all abstract methods from abstract classes or
interfaces.
● Abstraction hides the details of objects, details of implementation, details
of how to operate.
● Users just create about the APIs. (the input and output)
49. Overriding
Method overriding is a mechanism that allows a subclasses
to provide a specific implementation of a method
that is already provided by its super classes.
50. Overriding Rules
● The overriding method must have same name as in the super class
● The overriding method must have same parameter list as in the super
class
● It must be IS-A relationship (inheritance)
● The access modifier of the overriding method must be the same or
larger scope than the overridden method in the super class
● private, static, or final methods can NOT be overridden.
52. Overloading
● Method overloading is a powerful mechanism that allows us to define
cohesive class APIs.
● Method overloading can be implemented in 2 different ways:
○ Implement two or more methods that have the same name but take different
numbers of arguments
○ Implement two or more methods that have the same name but take arguments of
different types
● It’s NOT possible to have two method implementations that differ only in
their return types.
61. Passing Variables in Java
the Java Language Specification declares that the passing of all data (both
object and primitive), is defined by the following rule:
All data is passed BY VALUE
62. Passing Primitive Variables
In the case of primitive values, the value is simply the actual data associated
with the primitive (.e.g 1, 20.7, true, etc.) and the value of the data is copied
each time it is passed.
63. Passing Object Reference Variables
● The value associated with an object is actually a pointer, called a reference, to the
object in memory.
● If you're passing an object reference variable, you're passing a copy of the bits
representing the reference to an object.
● Two identical reference variables refer to the exact same object, if the called
method modifies the object, the caller will see that the object the caller's original
variable refers to has also been changed.
● The called method can NOT reassign the caller's original reference variable and
make it refer to a different object or null.
65. Passing Object Reference Variables
Java manipulates objects “by reference”,
but it passes object references to methods “by value”.
-- O'Reilly's Java in a Nutshell by David Flanagan
67. String
● String is a sequence of characters placed in the double quote (“ ”).
● The Java platform provides the “String class” to create and manipulates
strings.
68. Strings are Immutable Objects
● Strings are Objects
○ String could be considered a primitive type in Java, but in fact they are not.
○ String objects are actually made up of an array of char primitives.
● Strings are Immutable
○ Once a String object is created, it can NOT be modified.
○ For mutable string, we can use StringBuffer and StringBuilder classes.
(An object whose state can NOT be changed after it is created is known as an Immutable object. String,
Integer, Float, Double,... and all other wrapper classes’ objects are immutable)
69. How to create String objects
Two ways to create String objects:
1. By string literal
2. By the new keyword
70. How to create String objects
1. By string literal
For example:
● String s1 = “welcome”; // creates one String object and one reference variable
● String s2 = “welcome”; // no new object will be created
2. By the new keyword
For example:
● String s3 = new String(“welcome”); // creates two objects, and one reference variable
71. String Pool
● String Pool is a special area of memory inside the Java Heap Memory,
used to store String literals.
● Each time the JVM encounters a String literal, it checks the pool first to see
if an identical String are already exists.
● If the String already exists in the pool, a reference to the pooled instance
returns.
● If the String doesn’t exist in the pool, a new String object instantiates, then
is placed in the pool.
72. String Constructors
● No Argument Constructors:
○ No-argument constructor creates an empty String. Rarely used.
○ Example: String empty = new String();
● Copy Constructors:
○ Copy constructor creates a copy of an existing String . Also rarely used.
○ Example:
String word = new String("Java");
String word2 = new String(word);
● Other Constructors:
○ Most other constructors take an array as a parameter to create a String.
○ Example:
char[] letters = {'J', 'a', 'v', 'a'};
String word = new String(letters); //"Java”
73. Important operations of Strings
● String Concatenation
● String Comparison
● Substring
● Length of String
76. Substring
● A part of string is called substring. In other words, substring is a subset of
another string.
● We can get substring from the given string object by one of the two
methods:
○ public String substring(int startIndex)
○ public String substring(int startIndex, int endIndex)
77. Length of Strings
The String's length() method finds the length of the string. It returns count of
total number of characters.
80. Disadvantages of Immutability
● Less efficient - you need to create a new string and throw away the old
one even for small changes.
● Example:
String word = “Java";
word = word + “technologies”;
81. StringBuffer and StringBuilder
● Limitation of String?
○ String is slow and consumes a lot of memory when you concatenate too many strings
because every time it creates new instance.
● What is mutable string?
○ A string that can be modified or changed is known as mutable string.
○ StringBuffer and StringBuilder classes are used for creating mutable string.
● Differences between String and StringBuffer/StringBuilder?
○ String is immutable while StringBuffer/StringBuilder is mutable.
○ String is slower and consumes more memory while StringBuffer/StringBuilder is faster
and consumes less memory.
82. StringBuffer
● StringBuffer is a synchronized and allows us to mutate the string.
● StringBuffer has many utility methods to manipulate the string.
● This is more useful when using in a multi-threaded environment.
● Always modified in same memory location.
83. StringBuilder
● StringBuilder is the same as the StringBuffer class.
● However, the StringBuilder class is NOT synchronized and hence in a
single-threaded environment.
● The overhead is less than using a StringBuffer.