0% found this document useful (0 votes)
12 views6 pages

Java Object-Oriented Data Structures

The document discusses key concepts in object-oriented programming including classes, objects, encapsulation, inheritance, and polymorphism. It defines classes as templates that define the data and behavior of objects. Objects are instances of classes that reserve memory and can be manipulated. Encapsulation involves restricting access to class members to protect data and promote flexibility. Inheritance allows a derived class to inherit attributes and behaviors from a base class. Polymorphism enables different subclasses to define their own implementation of a method.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views6 pages

Java Object-Oriented Data Structures

The document discusses key concepts in object-oriented programming including classes, objects, encapsulation, inheritance, and polymorphism. It defines classes as templates that define the data and behavior of objects. Objects are instances of classes that reserve memory and can be manipulated. Encapsulation involves restricting access to class members to protect data and promote flexibility. Inheritance allows a derived class to inherit attributes and behaviors from a base class. Polymorphism enables different subclasses to define their own implementation of a method.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

• protects and manages its own information

• Class name should begin with a capital letter


• Put one class definition in each file
• One class is designated as startup class (main class) - contains main
method where the execution of the program begins
• Members of a class- data declarations/data fields and method
declarations
a. Data Fields
• Can be either class variables or instance variables
• If not declared the value "=0" will be the default value "0",
boolean=false, String = null
Syntax of data fields
<visibility access> <modifier> <datatype> <field name> = <value>;
c. Object (instance)
• Not for the class variables
• Objects are mutable (modified or changed)- can change the
contents of an object by making an assignment to one of its
instance variables
• Aliasing- when two variables are aliased, any changes that affect
one variables also affect the other, When you assign an object to a
variable, you are assigning a reference to an object
• Null: When you create an object variable, you are creating a
reference to an object, Until you make the variable point to an
object, the value of the variable is null.
• Garbage Collection: If no one refers to an object, then no one can
read or write any of its values, or invoke a method on it
• Primitives
Attributes- data fields
Operations- methods
d. Instantiation
• To give the actual value to the objects
• In main method
• e.g.
<object> <variable> = new <object>();
e. Visibility/ access modifiers
Public- can be directly referenced from outside of the object
Private- can be used anywhere inside the class definition but cannot be
referenced externally
- Instance variable should be defined with private visibility-can be accessed
only by the methods of the class
- violate encapsulation-allow code external to the class access or modify
the value of the data
Protected- relevant only in the context of inheritance
Default-the same as private
Variables: (public)- violates encapsulation
(private)- enforce encapsulation
Methods: (public)- provide services to clients
(private)- support other methods in the class
Inheritance information hiding
- The subclass inherit all the data and methods of the superclass
- Classes that directly use fields from parents classes are fragile (prone to
error/easy to break)
Protected access- provides an intermediate level of security between
public and private (can be used within its own class, but it cannot be used
by outside classes)
f. Class variables(static variable)
• Associated with the class itself rather than individual instances
• Memory space is established when the class that contains it is

Final OOP Page 1


• Memory space is established when the class that contains it is
referenced for the first time in a program
• Constants (Final modifier) are often declared using static modifier-
because the value of constants cannot be changed
<private/public/protected> static <datatype> <class variable>;
g. Instance variables
• New memory space is reserved for that variable every time an
instance of the class is created
• Should be private visibility, or not will violate encapsulation
Syntax of Instance Variable
<private/public/protected> <datatype> <instance variable>;
h. Constructors
• initialize instance variables
• Syntax is similar to method except: 1) the name of the constructor
is the same as the name of the class, constructor have no return
type and no return value, the keyword static is omitted
• Can be overloaded: Can provide multiple constructors with
different parameters
• It is common to have: one constructor that takes no argument; and
one constructor that takes a parameter list identical to the list of
instance variables
• Use of 'this' keyword to refer to the current instance of the class
i. This' keyword
• A reference variable that refers to the current object within an
instance method or a constructor
Uses:
1. Distinguishing instance variables and local variables
- In methods or constructor, If there is a local variable with the same name
as an instance variable, 'this' will refer to the instance variable
// Constructor with a parameter named "value"
public Example(int value) {
// Using "this" to refer to the instance variable
[Link] = value;
2. Invoking current object's method
- In instance method, 'this' Is to invoke another method of the current
object. This is useful when you want to call another method from within
the same class
public void printNumber() {
// Invoking another method using "this"
[Link]("Number: " + [Link]());
}
public int getNumber() {
return [Link];
3. Passing the current object as a parameter
- Pass the current object as parameter to another method or constructor
j. Instance methods
• Operates on an instance variables of a class
• Commonly used to define the behavior of objects and to perform actions
specific to individual instances
• Setters and getters methods are instance methods
Accessors- getters(getX)
• To retrieve values of instance variables
Mutators- setters(setX)
• To modify a particular value of instance variables
k. Static methods
• Operate on class level
• Accessed using the class name in main method
• Don't need to instantiate an object of the class in order to invoke the

Final OOP Page 2


• Don't need to instantiate an object of the class in order to invoke the
method
• Main method use declared with the static modifier
• No access to instance variable
• No "this" reference
• Can refer static variables
l. Sample of complete code
public class Student {
// Class variable (static)
static int totalStudents = 0;
// Instance variables
private String name;
// Constructors
public Student(String name, int age) {
// Using "this" keyword in the constructor
[Link] = name;
// Incrementing totalStudents on each instantiation
totalStudents++;
}
// Static method
public static int getTotalStudents() {
return totalStudents;
}
// Instance methods (getters and setters)
public String getName() {
return name;
}
public void setName(String name) {
// Using "this" keyword to refer to the instance variable
[Link] = name;
}
// Instance method using "this" to pass the current object
public void printStudentDetails() {
[Link]("Age: " + [Link]);
}
// Main method for instantiation and invoking instance methods
public static void main(String[] args) {
// Instantiating objects
Student student1 = new Student("Alice", 20);
// Invoking instance methods
[Link]();
// Accessing static method
int total = [Link]();
[Link]("Total Students: " + total);
2. Encapsulation
- a piece of code and wrapping it up in a method
• Abstraction: using a method name to contain or encapsulate a series of
statements
• A general method name in a module is used rather than list all the
detailed activities that will be carried out by the method
Class Relationships
Association
: the relationship between multiple objects (how they are using each
other's functionality)

Aggregation
: represent HAS-A relationship
• A weak association:

Final OOP Page 3


• A weak association:
• A class contains one or more members of another class, when those
members would continue to exist without the object that contains them

Composition
• A strong association
• A class contains one or more members or another class, when those
members would not continue to exist without the object that contains
them

3. Inheritance
• A mechanism that enables one class to acquire all the behaviors and
attributes of another class
• Save time because the Employee fields and methods already exist
• Reduce errors because the employee methods already have been used
and tested
• Reduce the amount of new learning required for programmers to use
the new class if they already are familiar with the original class
Base class (Employee) - class that is used as a basis for inheritance
Derived class (EmployeeWithTerritory) - class that inherits from a base
class
- Always "is a" case or example of the more general base class
E.g. an EmployeeWithTerritory "is an" Employee
Extending Classes
- One-way proposition: child inherits from a parent, not the other way
around
- Subclasses are more specific than the superclass
- Use instanceof operator to determine whether an object is a member or
descendant of a class

Overriding Superclass Methods


- To override a field or method in a child class means to use the child's
version instead of the parent's version
Three types of methods that cannot override in a subclass: static
methods, final methods, methods within final classes
Polymorphism (many forms):
- Overriding- Each subclass method overrides any method in the parent
class that has both the same name and parameter list
- Overload- if the parent class method has the same name but a different
parameter list, the subclass method does not override the parent class
version (overload) any subclass object has access to both versions
- The plus sign (+)- operates differently depending on its operands
- subtype polymorphism- methods that work appropriately for subclasses
of the same parent class
@Override
- Let the compiler know that your intention is to override a method in the
parent class rather than create a method with a new signature
Calling constructors
- When a superclass contains a default constructor and a subclass object is
instantiated, the execution of the superclass constructor usually is
transparent

Final OOP Page 4


transparent

Super keyword
- Refers to the superclass of the class in which you use it
an Employee class has a constructor that requires threes arguments -
char, double, int
HourlyEmployee class is a subclass of Employee
- The super() statement must be the first statement in any subclass
constructor that uses it

Accessing superclass methods


- To access the parent class method if a method has been overridden but
you want to use the superclass version within the subclass

Final OOP Page 5


Final OOP Page 6

Common questions

Powered by AI

Access modifiers in OOP, such as private, enforce encapsulation by restricting access to the class's internal data. Instance variables are typically marked private, which means they cannot be directly accessed by code outside the class, allowing the class to control how its data is accessed and modified through public methods. This prevents external code from altering state in unintended ways, thereby maintaining integrity and security within the class design .

Inheritance allows a new class, called a subclass, to inherit attributes and methods from an existing class, known as a superclass. This promotes reusability, as developers can extend existing logic and functionalities without re-writing common code, thus saving time and reducing potential errors. It also simplifies maintenance and learning curves, as developers familiar with the base class can easily adapt to using the subclass .

The 'this' keyword in OOP allows instance methods and constructors to clearly distinguish between instance and local variables when they have the same name, ensuring there's no ambiguity in code referencing. It also enables chaining of methods within an instance and helps pass the current object as a parameter to other methods or constructors, thereby improving class design by utilizing object references effectively .

Aliasing occurs when two or more variables refer to the same object in memory, leading to unintended side effects if one variable modifies the object. This risk is mitigated by ensuring that methods do not alter shared objects or by explicitly copying objects before modification. Effective encapsulation and minimizing shared mutable state can also control aliasing, preserving object integrity across different parts of the application .

Polymorphism allows objects to be treated as instances of their parent class, enabling a single interface to invoke methods from any subclass. This flexibility allows developers to write more general code that can handle new subclasses with minimal changes, reducing code complexity and improving maintainability. Overriding lets subclasses provide specific implementations, while overloading allows methods with the same name but different parameters, enhancing customization and application diversity .

The 'super' keyword allows a subclass to call methods and constructors from its superclass, facilitating code reuse and overriding behaviors. In constructors, 'super()' must be the first statement to ensure superclass initialization logic is not bypassed. It provides a mechanism to explicitly invoke overridden superclass methods, allowing subclasses to augment rather than replace functionality from a superclass .

Constructors allow for setting up initial conditions for objects, automatically invoked when an object is created. They provide the means to set initial values for instance variables, ensuring objects start life in a predictable state. This might include default settings or parameters passed at creation, with overloading to offer different initialization paths for different scenarios .

Getters and setters enforce encapsulation by providing controlled access to private instance variables. Getters retrieve values, while setters modify them, allowing internal data representation changes without impacting external code. They ensure that variable access adheres to business rules and validation logic, maintaining object integrity and internal consistency while exposing necessary functionality .

Static methods operate at the class level, meaning they can be called without having an instance of the class, and they are accessed using the class name. They cannot access instance variables or instance methods directly since no specific object context is required. Instance methods, on the other hand, require an object of the class to be created, and they operate on that object's instance data, making them contextually bound to the object instance and capable of accessing object-specific data .

Composition represents a strong relationship where the contained object's lifecycle is tied to its containing object, meaning it cannot exist independently. Aggregation, however, is a weaker association allowing the contained object to exist independently. This distinction affects encapsulation and the autonomy of component classes within systems, impacting how objects manage their dependencies and relationships .

You might also like