Java OOP Flashcards
Advantages of OOP
easy concept - faster than procedural-oriented programming - reusable code - keep important data hidden
Object & class
Object have a state (color , sex , height …)(attributes) and behaviour (swim , fly , dance…)(methods) , a class is the blueprint of object (instance of class)(example : dog , human, car).
An object is a variable of class
Note !!!! A class doesn t take any byte of memory.
3 Steps to create an object
Declaration
Instantiation
Initialization
how many public class can we have in a source file
we can have only one public class (the one with the same name of source file) , but multiple default classes
“this” keyword
we use “this” keyword in constructor or an instance method to differentiate local variable (var) from instance variable (this.var) if they have the same name.
Call one type of constructor ( default with this() or parametrized with this(param) ) from
other in the same class. it is known as explicit constructor invocation.
public vs static method
public method need a new object instantiation but static access is direct without instantiation.
finalize() method
has this form :
protected void finalize(){
//code here
}
it is called before object destroyed by GC
protected is used to prevent access from outside class.This means u won t know when or if finalize() execute. if you re program ends before GC occurs , finalize() will not execute
Method overloading
have the same name but different parameter ( and also number of param )
Command line argument
it is the information that follows directly java program name in command line when it is executed.
($java program-name “…”)
Java Methods Variables Arguments (var-args)
typeName… parameterName
In the method declaration, you specify the type followed by an ellipsis (…). Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters must precede it.
Constructor
it is a special type of method which initialize an object when created or do some procedures
name of constructor is same as class
java create automatically a constructor even if u don t create it , it initialize all variables to 0.
Once u created a constructor , default constructor provided by java is not invoked.
concept of creating multiple constructor in same class is : constructor overloading.
constructor don t have return type . DON T EVEN USE VOID TYPE !!!!!!!!!!!!!!!!!!!!!
access modifiers can be used to set its visibility/accessibility.
Type of constructor
has 3 types :
default constructor VS No-args constructor: default is provided by compiler , but no args is defined manually by programmer and u can give edit values of variables or do more process
they both don t accept arguments
Parametrized constructor: constructor with one or more param
Java Inheritance
One of java oop concepts. it is when a class acquire properties ( attributes and methods ) of another class .
A subclass inherits properties of superclass by using extends keyword :
class Sub extends Super{}
Why we need inheritance ?
Code reusability
extensibility(extend functionnality of a class)
Method overriding require inheritance
Abstraction require inheritance
“super” keyword
“super” keyword is like “this” keyword which differenciate between the members of a subclass from a superclass if they have same names.
for var : super.variable
for method:super.method()
It is also used to invoke superclass constructor from subclass
default constructor: super()
constructor with param: super(values)
if a class inherited properties from another class, the subclass automatically acquire default constructor of super class.
Java inheritance (IS-A relationship) type
Java support only single inheritance ( doesn t support multiple inheritance) but can implements multiple interfaces.
Interface in java can extends multiple interfaces.
What is Aggregation in java ?
A relationship (HAS-A) between two classes where a class contains instance of another class(like binding a class to other in one way direction)
benefits : reusable code
Aggregation types
unidirectional : like above def
bidirectional : where each of class contains instance of other class
Polymorphism
is the ability of an object to take on many forms , allow us to perform multiple operations using the single name of any method (interface).
method overriding is one of polymorphism concepts
any object that can pass more than one IS-A test is polymorphic.
All java objects are polymorphic, because an object can pass IS-A with its own type and the class Object.
Polymorphism types
compile-time polymorphism: method overloading (static polymorphism).
runtime polymorphism: method overriding.
method overriding
occur when a subclass implement a parent class method based on its requirement (overriding it ) without changing name , type , return type.
method overloading
occur when a class has two or more methods with same name but different parameter (different type and number of arguments)
in method overloading return type must not change
What is abstraction in java ?
Its hidden implementation details from user. providing functionnalities only without giving how it is done (code).
How we achieve abstraction?
with abstract classes and interfaces
Abstract class rules
*may or may not contains abstract method ( methods without body : public void get() ).
*if it contains an abstract method it must be declared abstract
*cannot be instantiated.
*to use it you must inherit it from another class.
*if a class inherit abstract class it must implement all its abstract methods.
abstract method
-abstract keyword is used to declare method as abstract.
-abstract method have a method signature but no body , it ends with semi colon “;” and without curly braces “{}”.
-Any class inheriting the abstract class must either override the abstract method or declare itself as abstract.
Encapsulation
hidden data (variables) and code from other classes except for method which can access and modify data.
it is also known as data hiding.
How to achieve encapsulation ?
-declare variables as private .
-provide public getter and setter to view and modify variables values.
Benefits of encapsulation
-the field of a class can be made read-only (only getter) or write-only (only setter);
(or also fully encapsulated getter+setter)
-a class have total control over what is stored in its fields.
What is interface ?
We use interface to achieve abstraction.
Interface is also a reference type and is similar to the class.
However, a class describes states and behaviors of object . Interface contains behaviors that a class implements.
Interface contains constants , abstract methods(without body) ; and static and default methods ( the only ones with body).
Interface is like a contract
Class and interface similarities
-contains any number of methods
-Writting in .java extension , and have the same name of file
-byte code appears in .class file
-appears in packages, and their byte code appears in a directory structure that matches package name
Class and interface differences
-interface cannot be instantiated
-interface doesn t have a constructor
-method in interface is by default abstract , and field must be both static and final
-A class can implements( don’t extends) multiple interfaces
- an interface can extends multiple interfaces.
Properties of interface
-Interface is implicitly abstract, you don t need to declare abstract keyword , same thing for its methods.
-its methods are implicitly public.
What is tagging interface
Also known as marker interface , is an interface with no method and field on it
=> it’s an interface with empty body
What is tagging interface purpose
-Create a common parent(among a group of interfaces).
-Adds a data type to a class: class become interface type through polymorphism.
Packages
is a grouping of related types ( classes , interfaces , enumerations and annotations ) providing access protection and namespace management
Package types
Built-in packages
user-defined packages
Examples of Built-in packages
java.lang:bundles/gathers the fundamental classes
java.io: bundles classes for input and output functions (like System.in and System.out).
Why we use “Import” keyword Java ?
To make use of package we need to import it with import keyword.
Inner , outer and nested classes
Inner class is a class that is defined in another class , it works with nested classes where both inner and outer class exists . An outer class is the main class in which all inner classes are defined
static class
can be defined only inside outer class ( if it is a main/outer class or not a nested class it’s impossible to use static keyword)
we can access its members without instantiation we need only class name.
Anonymous class (classe anonyme)
Is a nameless inner class , and because it’s nameless ,it doesn t have a constructor because constructor have same name as its class.
Use of anonymous class
we mainly use it to instantiate interface (or an abstract class)
Type of anonymous class
*anonymous inner class that extends class
__________________________
*anonymous inner class that implements interface
for example :
public interface Soft{
public void dev();
}
=> Soft s=new Soft(){
//code here
public void dev(){
sout(“hi”);
}
}
s.dev();
______________________________
*anonymous inner class as argument
Singleton
is a design pattern , it’s a creational pattern.
This pattern involves only a single class which is responsible to create only one Object.this class provides a way to access it’s only object directly without the need to instantiate its object
Advantages of Singleton
it saves memory because only one object instance is created and it also provides global access to its instance
Use of Singleton
create classes related to database connection
Rules to create Singleton
private constructor(to defeat instantiation)
*instance attribute is private static + SingletonType
*method to return instance :getInstance() is public + SingletonType
3 common types of Singleton
*Eager Initialization: instance is already instantiated to new ClassName()
*Lazy Initialization: instance attribute is null at the beginning and we initialize instance on getInstance() after check it’s still null then we return it
*Thread-safe Singleton (syncronized method) : Lazy initialization + we use sychronized on getInstance();
Wrapper classes
are does whose object wraps a primitive data type within them (java.lang package contain them).
All wrapper classes (Integer,Float,Short,Byte, Double,Long) are subclasses of the abstract class number
Enum
is a special class which contains a group of pre-defined constant values and can be used in switch expressions for comparison.
By default an enum doesn’t require a constructor.
enum constructor+attribute scope
as enum is a special class, it can only have a private or package-private(without access modifier) constructor , if it’s public , it will trigger a compile time error
+ it’s attribute should be private final
some enum methods
toString(), name()
What is immutable class ?
Immutable class is a class whose objects cannot be modified after their creation
What is immutable class rules ?
*Final Class
*Final Fields
*No setters
*Deep copies : the class ensures making copy of object rather than storing reference to avoid external modification
Association vs Aggregation vs Composition ?
*Association is the most general form of relationship, where objects interact with each other but have no strong dependency.
*Aggregation is a “whole-part” relationship, but the parts can exist independently of the whole.
*Composition is a more tightly coupled form of aggregation, where the contained objects cannot exist without the whole object.
What is difference between composition and inheritance ?
*Composition is better for modeling “has-a” relationships where the lifecycle of the contained objects is tied to the lifecycle of the container. It promotes flexibility and loose coupling.
*Inheritance is better for “is-a” relationships where a subclass needs to extend or modify the behavior of a parent class. It promotes code reuse but can lead to tight coupling.