Ch07 OOP
Ch07 OOP
Java Programming
Eng,Awil Ahmed Abdi
+
Objectives
Chapter 7
Concept of OOP
Object and Classes in java
Constructors in java
Java OOP This keyword
+
Object-Oriented Programming (OOP)
Object
Class
Inheritance
Polymorphism
Abstract
Encapsulation
+
Object-Oriented Programming (OOP)
+
Java Classes/Objects
Everything in Java is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.
+
Java Classes/Objects
A class is declared using class keyword. A class contain both data and code
that operate on that data. The data or variables defined within a class are
called instance variables and the code that operates on this data is known
as methods.
Thus, the instance variables and methods are known as class members. class is
also known as a user defined datatype.
+
Java Classes/Objects
A class is declared using class keyword. A class contain both data and code that operate on that
data. The data or variables defined within a class are called instance variables and the code
that operates on this data is known as methods.
Thus, the instance variables and methods are known as class members. class is also known as
a user defined datatype.
Example.
int x = 5;
}
+
Java Classes/Objects
In Java, an object is created from a class. We have already created the class named MyClass, so
now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name, and use the
keyword new
Example.
A constructor is a special method that is used to initialize an object. Every class has a
constructor, if we don't explicitly declare a constructor for any java class the compiler builds a
default constructor for that class. A constructor does not have any return type.
A constructor has same name as the class in which it resides. Constructor in Java can not be
abstract, static, final or synchronized. These modifiers are not allowed for constructor.
+
Java Constructors
Example.
public class MyClass {
int x;
MyClass() {
x = 5;
}
public static void main(String[] args) {
MyClass myObj = new MyClass();
System.out.println(myObj.x);
}
}
+
Java Constructors
Example 1
Car c = new Car();
Constructor Parameters
Example 2