0% found this document useful (0 votes)
6 views13 pages

Java Object-Oriented Programming Basics

The document provides an overview of Object-Oriented Programming (OOP) in Java, covering key concepts such as classes, objects, constructors, access modifiers, the 'this' keyword, static members, method overloading, inheritance, and polymorphism. It includes examples to illustrate these concepts, such as defining a Dog class, creating objects, and using constructors for initialization. Additionally, it explains the use of the 'extends' keyword for inheritance and the 'super' keyword for accessing superclass members and methods.

Uploaded by

ahmadarada2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views13 pages

Java Object-Oriented Programming Basics

The document provides an overview of Object-Oriented Programming (OOP) in Java, covering key concepts such as classes, objects, constructors, access modifiers, the 'this' keyword, static members, method overloading, inheritance, and polymorphism. It includes examples to illustrate these concepts, such as defining a Dog class, creating objects, and using constructors for initialization. Additionally, it explains the use of the 'extends' keyword for inheritance and the 'super' keyword for accessing superclass members and methods.

Uploaded by

ahmadarada2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Tuesday, December 30, 2025 The University of Jordan Dr. Rami S.

Alkhawaldeh

Object-Oriented Programming in Java


Object-Oriented Programming is a programming model based on the concept of "objects", which
can contain data in the form of fields (often known as attributes or instance variables) and code in
the form of procedures (often known as methods).

1. Defining Classes
A class is a blueprint or a template for creating objects. It defines a set of properties and behaviors
that are common to all objects of that type. In Java, a class is defined using the class keyword.

Example: A Dog class Let's define a class named Dog. A dog has properties like name, breed,
and age, and it can perform actions like barking and wagging its tail.

public class Dog {


// Instance Variables
// Each object (or instance) of the class has its own distinct copy of
these variables.
String name;
String breed;
int age;
// Methods
void bark() {
[Link]("Woof! Woof!");
}
void displayInfo() {
[Link]("Name: " + name + ", Breed: "
+ breed + ", Age: " + age);
}
}

2. The new operator and Creating Objects


An object is a concrete entity created from a class. While the class is the blueprint, the object is the
actual house built from that blueprint. To create an object in Java, you use the new keyword. The
process of creating an object is called instantiation.

ClassName objectName = new ClassName();


Dog myDog1 = new Dog();
Dog myDog2 = new Dog();

Page 1 of 13
Tuesday, December 30, 2025 The University of Jordan Dr. Rami S. Alkhawaldeh

Example: Creating Dog objects


public class Main {
public static void main(String[] args) {
// Create a Dog object named myDog1
Dog myDog1 = new Dog();

// Assign values to its instance variables


[Link] = "Buddy";
[Link] = "Golden Retriever";
[Link] = 3;

// Create a second Dog object named myDog2


Dog myDog2 = new Dog();
[Link] = "Lucy";
[Link] = "Poodle";
[Link] = 5;

// Call methods on the objects


[Link]("First dog's info:");
[Link]();
// Output: Name: Buddy, Breed: Golden Retriever, Age: 3
[Link]("\n Second dog's info:");
[Link](); // Output: Name: Lucy, Breed: Poodle, Age: 5
}
}

3. Constructors
A constructor is a special method that is automatically called when an object is created using the
new keyword. Its primary purpose is to initialize the instance variables of the object.

§ Rules for Constructors:


1. A constructor has the exact same name as the class.
2. A constructor does not have a return type (not even void).

Page 2 of 13
Tuesday, December 30, 2025 The University of Jordan Dr. Rami S. Alkhawaldeh

Example: Adding a constructor to the Dog class Manually assigning values to each variable after
creating an object (like [Link] = "Buddy") can be tedious. A constructor streamlines this
process.

public class Dog {


String name;
String breed;
int age;

// This is the constructor for the Dog class


public Dog(String dogName, String dogBreed, int dogAge) {
[Link]("Constructor called!");
name = dogName;
breed = dogBreed;
age = dogAge;
}
void displayInfo() {
[Link]("Name: " + name + ", Breed: "
+ breed + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Create a Dog object using the constructor
// The values "Buddy", "Golden Retriever",
and 3 are passed to the constructor
Dog myDog = new Dog("Buddy", "Golden Retriever", 3);

// The object is already initialized, so we can just call the method


[Link]();
// Output: Name: Buddy, Breed: Golden Retriever, Age: 3
}
}

§ When new Dog(...) is executed, the Java runtime does three things:
1. Allocates memory for a new Dog object.
2. Calls the Dog constructor.
3. Returns a reference (the memory address) to the newly created object, which is then stored in
the myDog variable.

Page 3 of 13
Tuesday, December 30, 2025 The University of Jordan Dr. Rami S. Alkhawaldeh

4. Access Modifiers
In Java, access modifiers are keywords that set the accessibility or scope of a class, constructor,
variable, method, or data member; restricting access to some of the object's components.

There are four types of access modifiers in Java:

Modifier Access Level Description

Members are accessible only within the class


where they are declared. This is the strictest
private Class Only
level and is typically used for instance
variables to protect the object's state.

Members are accessible only within the same


Default
Package Only package. This is often called "package-
(No Modifier)
private."

Members are accessible within the same


Package and
protected package and by all subclasses (even if the
Subclasses
subclass is in a different package).

Members are accessible from any other class.


This is the least restrictive level and is typically
public Everywhere
used for methods that form the public interface
of the class.
(If no modifier is specified, it is treated as default)

5. The this Keyword


The this keyword is a reference variable in Java that refers to the current object. It's used inside a method or
constructor to eliminate ambiguity between instance variables and parameters that have the same name.

Main uses of this:

1. To distinguish instance variables from local parameters: This is the most common use.
2. To invoke a constructor from another constructor in the same class (constructor chaining).
3. To pass the current object as an argument to another method.

Page 4 of 13
Tuesday, December 30, 2025 The University of Jordan Dr. Rami S. Alkhawaldeh

Let's refine our Dog constructor. It's common to name parameters the same as the instance variables they
are initializing.

public class Dog {


private String name;
private int age;
// The parameters 'name' and 'age' have
the same name as the instance variables.
public Dog(String name, int age) {
// '[Link]' refers to the instance variable of the object.
// 'name' refers to the parameter passed to the constructor.
[Link] = name;
[Link] = age;
}
public void displayInfo() {
// Here, 'this' is optional because there is no ambiguity.
[Link]("Name: " + [Link] + ", Age: " + [Link]);
}
}
Without this, the assignment name = name; would simply assign the parameter to itself, leaving the instance
variable unchanged (and still null).

The primary uses of this are:

 To Differentiate Instance Variables from Local Variables: When a local variable (like a method
parameter) has the same name as an instance variable, [Link] is used to refer to the
instance variable.
public class Box {
private int width;
public Box(int width) {
[Link] = width; // '[Link]' refers to the instance
variable
}
}

 To Invoke the Current Class's Constructor (Constructor Chaining): The this(...) call is used inside one
constructor to call another constructor in the same class. This must be the first statement in the
constructor.
public class Box {
public Box() {
this(10); // Calls the parameterized constructor below
}

Page 5 of 13
Tuesday, December 30, 2025 The University of Jordan Dr. Rami S. Alkhawaldeh

public Box(int width) {


[Link] = width;
}
}

 To Return the Current Class Instance: Used to return the current object from a method, often for
method chaining (fluent interface).
public class MethodChaining {
public static class Calculator {
private int value;

public Calculator(int initialValue) {


[Link] = initialValue;
}
public Calculator add(int num) {
[Link] += num;
return this; // Key to method chaining
}
public Calculator subtract(int num) {
[Link] -= num;
return this; // Key to method chaining
}
public int equals() {
return [Link];
}
}
public static void main(String[] args) {
// Calculation: Start at 10, then +5, then -2, then +100
int result = new Calculator(10)
.add(5)
.subtract(2)
.add(100)
.equals(); // Final call to get the value
[Link]("The final result is: " + result);
// Output: The final result is: 113
}
}

Page 6 of 13
Tuesday, December 30, 2025 The University of Jordan Dr. Rami S. Alkhawaldeh

6. Static Members (Variables and Methods)


The static keyword is used to create variables and methods that belong to the class itself, rather than to any
specific object (instance) (shared among all instances of a class). There is only one copy of a static variable,
regardless of how many objects are created.

Example1: Counting the number of Dog objects created

public class Dog {


private String name;
// This static variable is shared by all Dog objects.
public static int dogCount = 0;
public Dog(String name) {
[Link] = name;
dogCount++;
}
}
public class Main {
public static void main(String[] args) {
// Access via the class name
[Link]("Initial dog count: " + [Link]);
Dog dog1 = new Dog("Buddy");
[Link]("After creating dog1: " + [Link]);
Dog dog2 = new Dog("Lucy");
[Link]("After creating dog2: " + [Link]);
}
}

Key restriction: A static method can only access static variables and call other static methods. It cannot
access instance variables or instance methods because it is not associated with any specific object. In
addition, they cannot use the this or super keywords.

Example2: A utility method

public class MathHelper {


public static final double PI = 3.14159; // Static constant
// This is a static method. You don't need a MathHelper object to call
it.
public static int add(int a, int b) {
return a + b;
}
}

Page 7 of 13
Tuesday, December 30, 2025 The University of Jordan Dr. Rami S. Alkhawaldeh

public class Main {


public static void main(String[] args) {
// Call the static method directly on the class.
int sum = [Link](5, 10);
[Link]("Sum: " + sum); // Output: Sum: 15
// Access the static variable directly on the class.
[Link]("Value of PI: " + [Link]);
}
}

7. Method Overloading
Method Overloading is a feature that allows a class to have more than one method with the same name,
provided that their parameter lists are different. This is an example of Compile-time Polymorphism.

The parameter lists must differ in at least one of the following ways:

 Number of parameters:
void display(int a) { ... }
void display(int a, int b) { ... }

 Data type of parameters:


void print(int i) { ... }
void print(String s) { ... }

 Order of parameters (if types are different):


void show(int a, String b) { ... }
void show(String b, int a) { ... }

Note: Method overloading is not determined by the return type or the access modifier. The compiler uses the
method name and the types/number of arguments to decide which method to call at compile time.

8. The extends keyword, Superclasses and Subclasses, the super


keyword, and Constructor Chaining.
1. The extends Keyword and Superclasses/Subclasses

Inheritance is the mechanism in Java by which one class is allowed to inherit the features (fields and
methods) of another class. The primary goal of inheritance is to promote code reusability and establish a
clear "is-a" relationship between classes.

extends Keyword: This keyword is used in the class declaration to indicate that a new class is inheriting from
an existing class. Java supports single inheritance, meaning a class can only extend one other class.

Page 8 of 13
Tuesday, December 30, 2025 The University of Jordan Dr. Rami S. Alkhawaldeh

class Subclass extends Superclass {// ... members of Subclass}

 Superclass (Parent Class): The class whose features are inherited.


 Subclass (Child Class): The class that inherits the features of the superclass. The subclass can add
its own unique features and can also override (redefine) inherited methods.

Example:

class Vehicle { // Superclass

String brand = "Ford";


public void honk() {
[Link]("Tuut, tuut!");
}
}
class Car extends Vehicle { // Subclass
String modelName = "Mustang";
}

In this example, Car is a subclass of Vehicle. A Car object automatically has the brand field and the honk()
method from Vehicle.

2. The super Keyword

The super keyword is a reference variable that is used inside a subclass to refer to the immediate superclass
object. It serves three main purposes:

 To refer to immediate superclass instance variables: If a subclass has a variable with the same
name as a variable in its superclass, [Link] is used to access the superclass's version.
 To call immediate superclass methods: If a subclass overrides a method from its
superclass, [Link]() is used to call the superclass's implementation of that method.
 To call immediate superclass constructors: This is the most common and critical use, leading
to Constructor Chaining (explained below).

Example:

class Animal {
Animal(String type) {
[Link]("An Animal of type: " + type + " is created.");
}
}

class Dog extends Animal {

Page 9 of 13
Tuesday, December 30, 2025 The University of Jordan Dr. Rami S. Alkhawaldeh

Dog() {
super("Canine"); // Calls the Animal(String) constructor
[Link]("A Dog is created.");
}
}

3. Constructor Chaining

Constructor Chaining is the process of calling one constructor from another constructor. In the context of
inheritance, it specifically refers to the mechanism that ensures the superclass's constructor is executed
before the subclass's constructor.

 The Rule: In Java, every subclass constructor must explicitly or implicitly call a constructor of its
immediate superclass. This is essential because the superclass constructor is responsible for
initializing the inherited members of the object.
 Explicit Invocation: You use super(...) as the very first statement in the subclass constructor to
explicitly call a specific superclass constructor.
 Implicit Invocation: If you do not include super(...) as the first statement, the Java compiler
automatically inserts a call to the superclass's no-argument constructor (super();). If the superclass
does not have a no-argument constructor, the compiler will report an error, forcing you to explicitly
call one of the available superclass constructors.

Example of Constructor Chaining:

class Parent {
Parent(int value) {
[Link]("Parent constructor called with value: " + value);
}
}

class Child extends Parent {


Child() {
// Implicitly, the compiler would try to insert super();
// But since Parent only has a parameterized constructor, we must
call it explicitly:
super(10); // Explicitly calls Parent(int)
[Link]("Child constructor called.");
}
}

Page 10 of 13
Tuesday, December 30, 2025 The University of Jordan Dr. Rami S. Alkhawaldeh

This chaining ensures that the object is initialized from the top of the hierarchy down to the current class,
maintaining the integrity of the object's state.

9. Polymorphism
1. Abstract

An abstract class in Java is a class that cannot be instantiated on its own and must be subclassed by
another class to be used. It can contain both abstract methods (methods without a body) and concrete
methods (methods with a body).
 Cannot be instantiated: You cannot create an object of an abstract class directly.
 Can have abstract and non-abstract methods: Abstract classes can have a mix of methods with
and without implementations.
 Can have constructors, static methods, and final methods: Abstract classes can have
constructors, which are called when a subclass is instantiated.
 Can have instance variables: Abstract classes can have instance variables (fields) that are
not static or final.
 Subclasses use extends: A class inherits from an abstract class using the extends keyword.
 Single inheritance: A class can only extend one abstract class.

2. Interfaces

An interface in Java is a completely abstract type that is used to group related methods with empty bodies. It
defines a contract that a class must adhere to if it implements the interface.
 Cannot be instantiated: You cannot create an object of an interface.
 All methods are implicitly public and abstract: Before Java 8, all methods in an interface were
abstract. Java 8 introduced default and static methods, which can have implementations.
 All variables are implicitly public, static, and final: Interfaces can only have constants.
 Subclasses use implements: A class implements an interface using the implements keyword.
 Multiple inheritance: A class can implement multiple interfaces.

Feature Abstract Class Interface


Instantiation Cannot be instantiated Cannot be instantiated directly.
directly.
Methods Can have abstract and All methods are public and abstract by default. Can have
concrete methods. default and static methods with implementation (Java 8+).
Variables Can have instance Can only have public, static, and final constants.
variables.
Constructor Can have constructors. Cannot have constructors.
s
Inheritance A class can extend only A class can implement multiple interfaces.
one abstract class.
Keyword extends implements

Page 11 of 13
Tuesday, December 30, 2025 The University of Jordan Dr. Rami S. Alkhawaldeh

3. Diamond Problem

The Diamond Problem is a classic issue in object-oriented programming, particularly in languages that allow
multiple inheritance. It describes the ambiguity that arises when a class inherits from two or more classes
that have a common ancestor.

interface Animal {
default void makeSound()
{
}
}

interface Lion extends Animal interface Tiger extends Animal


{ {
@Override @Override
default void makeSound() default void makeSound()
{} {}

class Liger implements Lion, Tiger {


@Override
public void makeSound() {
// You can choose one of the parent implementations
explicitly
[Link]();
[Link]();
// Or provide a completely new one
[Link]("The liger makes a unique sound!");
}
}

 Java was designed to avoid this problem by not allowing multiple inheritance of classes. A Java class
can only extend one parent class. This design choice completely sidesteps the Diamond Problem for
classes.
 However, the Diamond Problem can still conceptually appear with interfaces. A Java class can
implement multiple interfaces.
 If we try to create the Liger class without overriding makeSound(), the Java compiler will throw an
error because it doesn't know whether to use the implementation from Lion or Tiger.

Page 12 of 13
Tuesday, December 30, 2025 The University of Jordan Dr. Rami S. Alkhawaldeh

 To resolve the conflict, the Liger class must provide its own makeSound() method. This makes the
choice explicit and resolves the ambiguity.
 In summary, Java avoids the Diamond Problem with classes by disallowing multiple inheritance and
resolves it for interfaces by forcing the implementing class to provide its own implementation if there's
a conflict.

UML: [Link]
diagram-tutorial/

Page 13 of 13

You might also like