OOPs Concepts v.0.2
(1) JAVA Source File Structure. 24/08/2022
- A java program can contain at most 1 public class with any number of non-public classes.
- A java program must be save as public class name. example as Program - 1.2.
- Since there is no public class in Program - 1 So, we can give any name to our java program.
- For every non-public classes there will be same number of .class file generated.
PROGRAM - 1.1 PROGRAM - 1.2
class A { } public class Deep { }
class B { } class B { }
class C { } class C { }
PROGRAM NAME-- codingHater.java Deep.java
*More then one public class will result in Compile Time Error.
{
//anyName.java == FileName //(E.g:- PROGRAM - 1.1)
}
else if(public_class == 1)
---------------------------- Given => Deepesh.java Program -----------------------------------------
E.g:- A.class, B.class, C.class and D.class ......after (1)
(2) JAVA Import Statement
(2.1) Explicit Import (2.2) Implicit Import- * (I-star)
java.util.arraylist java.util.*
Points to be remember...
- Class present in a sub packages required the complete address of sub package to be imported.
Example- For ArrayList (import java.util.*) is right way not (import java.*) - All classes present under current working directory required NO import statement.
Example- Util class in JAVA. - The root folder of your current Java project is CWD.
String cwd = System.getProperty("user.dir");
(3) JAVA Package Statement 1-P.I.C
PACKAGE-Encapsulation way to grouping out same data together.
Ex- Folder structure in computer.
- A java program can contain at most 1 package statement only.
- PIC- order of program execution be Package, Import, Classes/Interfaces/Enum
javac -d . program.java
(java bhai compile kar do, -d current working directory of package ke java program ko)
IMPORTANCE:-
- Naming-Configuration
- Maintainability
- Modularity(Modification)
- Security
(4) Class Level Modifiers
( PRIVATE > DEFAULT > PROTECTED > PUBLIC )
Public- Global, Private-Class==level, Protected-D+Child, Default-Package
}
}
Public is recommended modifier for storing Method.
4.1 Public- Global level, Class can be accessible from any where.
4.2 Default- Package level, Within the same package only.
4.3 Abstract- Object creation (Instantiation) is not possible.
4.4 Final- Child class creation not possible.
4.5 Strictfp
For Inner classes 4.1 to 4.5 +
Private is recommended modifier for storing Variable. In order to stop data accessibility.
4.6 Private- Class level- Jinki class apne level ki ho.
4.7 Protected- Default + KIDS-- CHILD class reference will be taken only... if outside the package.
public class TestSimpleCircle {
class SimpleCircle {
double radius;
SimpleCircle(){
radius = 1;
} }
public static void main(String [] args) {
SimpleCircle circle = new SimpleCircle();
System.out.println("the area of the circle of radius "+circle.radius+" is "+circle.getArea());
}
}
SimpleCircle
is an inner class of class TestSimpleCircle
. This means that you first need an instance of object of enclosing class, for example:TestSimpleCircle tsc = new TestSimpleCircle();
Now you are able to create an instance of inner class that is connected with an instance of enclosing
TestSimpleCircle
class:SimpleCircle sc = tsc.new SimpleCircle();
As you see, to create an instance of object of inner class you had to specify to which exactly object of enclosing class you want it to belong (with the
tsc.new
in your example).If you need to create an instance of SimpleCircle without instance of object of enclosing class you should have declared this class as
static class SimpleCircle{code of your class here}
package com.protect;
public class Bike
{
protected int tire = 0;
protected int wheels(int tire)
{
this.tire = tire;
return tire;
}
public static class Auto
{
static Bike auto = new Bike(); //4.7
static int n = auto.wheels(3);
public static void tire() {
try { System.out.println(n); }
catch (Exception e)
{ e.printStackTrace(); }
}
} }
//////////////////////////////////////////////////////////MAIN CLASS ///////////////////////////////////////////////////////////////
public class Main extends Bike {
public static void main(String[] args) {
Main mn = new Main();
mn.wheels(3);
System.out.println(mn.wheels(4));
4.8 Static Bike.Auto.tire();
} }
4.8 Static What we should know about static modifier:-
- we CANNOT access non-static members of a class within a static context,
such as a static method or block. Compiling the code below will result in an error:-
public class Counter {
private int count;
public static void main(String args []) {
System.out.println(count); // Compile time error
}}
- static fields and methods are NOT thread safe, causes security problems in multithreading cases.
Considering that each instance of a class references the same copy of a static variable,
such a variable needs to be protected or "locked" by the class. Therefore, when using static variables, be sure that they are properly SYNCHRONIZED to avoid problems such as race conditions.
- No need to create a new object each time you want to call them, A static method
can be called using the name of the class that declares it.
these methods are perfect for
factory
methods and utility
methods.
example- java.lang.Math
- you can't override (
@Override
) static methods. If you declare such a method in a subclass
, i.e. a method with the same name and signature, you just "hide" the method of the SUPER class, This phenomenon is known as method hiding.
class Vehicle {
public static void kmToMiles(int km) {
System.out.println("Inside the parent class / static method");
}
}
class Car extends Vehicle {
public static void kmToMiles(int km) {
System.out.println("Inside the child class / static method");
}
}
public class Demo {
public static void main(String args []) {
Vehicle v = new Car();
v.kmToMiles(10);
}
}
Console output:
Inside the parent class / static method
the object is a Car
, the static method in the Vehicle
class is called, since the method was called at compile time.
- We can declare classes static. It is worth noting that, like inner classes,
static nested classes are declared in a separate .class file.
Thus, if you declare five nested classes in your main class,
you will have 6 files with the .class extension.
- The static modifier can also be specified in a static block, better known
as a "static initialization block", which is executed when the class is loaded.
- It's useful to know that static methods are linked at compile time, unlike the
linking of virtual or non-static methods, which are linked at run time when
called on a real object. Accordingly, static methods cannot be overridden in Java,
since polymorphism does not apply to them at run time.
- Initialization is an important aspect of a static block. Static fields or variables are
initialized after the class is loaded into memory.
This means that the static field will be initialized even BEFORE someone "asks"
for it. If an object is resource-heavy or rarely used, then initializing it in a static
block won't work in your favor.
During serialization, static fields, like transient
variables, are not serialized. Indeed, if you save any data in a static field, it will contain its initial (default) value after deserialization. For example, if a static field is an int
, its value will be zero after deserialization. If its type is float
, the value will be 0.0. If the field is an Object
, the value will be null
. To be honest, this is one of the most frequently asked questions about serialization in interviews for Java positions. Don't store essential object data in a static field!
Finally, let's talk about static import. This modifier has a lot in common with the standard import
statement, but it is different in that it lets you mport one or all static class members. Once static methods are imported, they can be accessed as if they were declared in the same class. Similarly, by importing static fields, we can access them without specifying the class name. This feature appeared in Java 1.5 and improves code readability when used properly. This construct is found most often in JUnit tests, since almost all test developers use static import for assert methods, e.g. assertEquals()
and their overloaded variants.
factory
methods and utility
methods.example- java.lang.Math
@Override
) static methods. If you declare such a method in a subclass
, i.e. a method with the same name and signature, you just "hide" the method of the SUPER class, This phenomenon is known as method hiding.
class Vehicle {
public static void kmToMiles(int km) {
System.out.println("Inside the parent class / static method");
}
}
class Car extends Vehicle {
public static void kmToMiles(int km) {
System.out.println("Inside the child class / static method");
}
}
public class Demo {
public static void main(String args []) {
Vehicle v = new Car();
v.kmToMiles(10);
}
}
Console output:
Inside the parent class / static method
the object is aCar
, the static method in the Vehicle
class is called, since the method was called at compile time.During serialization, static fields, like transient
variables, are not serialized. Indeed, if you save any data in a static field, it will contain its initial (default) value after deserialization. For example, if a static field is an int
, its value will be zero after deserialization. If its type is float
, the value will be 0.0. If the field is an Object
, the value will be null
. To be honest, this is one of the most frequently asked questions about serialization in interviews for Java positions. Don't store essential object data in a static field!
Finally, let's talk about static import. This modifier has a lot in common with the standard import
statement, but it is different in that it lets you mport one or all static class members. Once static methods are imported, they can be accessed as if they were declared in the same class. Similarly, by importing static fields, we can access them without specifying the class name. This feature appeared in Java 1.5 and improves code readability when used properly. This construct is found most often in JUnit tests, since almost all test developers use static import for assert methods, e.g. assertEquals()
and their overloaded variants.
- we CANNOT access non-static members of a class within a static context, such as a static method or block. Compiling the code below will result in an error:- public class Counter { private int count; public static void main(String args []) { System.out.println(count); // Compile time error }}
- static fields and methods are NOT thread safe, causes security problems in multithreading cases. Considering that each instance of a class references the same copy of a static variable, such a variable needs to be protected or "locked" by the class. Therefore, when using static variables, be sure that they are properly SYNCHRONIZED to avoid problems such as race conditions.
- No need to create a new object each time you want to call them, A static method
can be called using the name of the class that declares it.
these methods are perfect for
factory
methods andutility
methods.
example- java.lang.Math - you can't override (
@Override
) static methods. If you declare such a method in asubclass
, i.e. a method with the same name and signature, you just "hide" the method of the SUPER class, This phenomenon is known as method hiding. class Vehicle { public static void kmToMiles(int km) { System.out.println("Inside the parent class / static method"); } } class Car extends Vehicle { public static void kmToMiles(int km) { System.out.println("Inside the child class / static method"); } } public class Demo { public static void main(String args []) { Vehicle v = new Car(); v.kmToMiles(10); } }Console output:
Inside the parent class / static method
the object is aCar
, the static method in theVehicle
class is called, since the method was called at compile time.
- We can declare classes static. It is worth noting that, like inner classes, static nested classes are declared in a separate .class file. Thus, if you declare five nested classes in your main class, you will have 6 files with the .class extension.
- The static modifier can also be specified in a static block, better known as a "static initialization block", which is executed when the class is loaded.
- It's useful to know that static methods are linked at compile time, unlike the linking of virtual or non-static methods, which are linked at run time when called on a real object. Accordingly, static methods cannot be overridden in Java, since polymorphism does not apply to them at run time.
- Initialization is an important aspect of a static block. Static fields or variables are initialized after the class is loaded into memory. This means that the static field will be initialized even BEFORE someone "asks" for it. If an object is resource-heavy or rarely used, then initializing it in a static block won't work in your favor.
During serialization, static fields, like
transient
variables, are not serialized. Indeed, if you save any data in a static field, it will contain its initial (default) value after deserialization. For example, if a static field is anint
, its value will be zero after deserialization. If its type isfloat
, the value will be 0.0. If the field is anObject
, the value will benull
. To be honest, this is one of the most frequently asked questions about serialization in interviews for Java positions. Don't store essential object data in a static field!Finally, let's talk about static import. This modifier has a lot in common with the standard
import
statement, but it is different in that it lets you mport one or all static class members. Once static methods are imported, they can be accessed as if they were declared in the same class. Similarly, by importing static fields, we can access them without specifying the class name. This feature appeared in Java 1.5 and improves code readability when used properly. This construct is found most often in JUnit tests, since almost all test developers use static import for assert methods, e.g.assertEquals()
and their overloaded variants.
WHAT IS JAVA?
Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure programming language.
developed by Sun Microsystems (which is now the subsidiary of Oracle)
Java has a runtime environment (JRE) and API, it is called a platform.
developed by Sun Microsystems (which is now the subsidiary of Oracle)
Java has a runtime environment (JRE) and API, it is called a platform.
Application
- Desktop Applications such as acrobat reader, media player, antivirus, etc.
- Web Applications such as irctc.co.in, javatpoint.com, etc.
- Enterprise Applications such as banking applications.
- Mobile
- Embedded System
- Smart Card
- Robotics
- Games, etc.
- Desktop Applications such as acrobat reader, media player, antivirus, etc.
- Web Applications such as irctc.co.in, javatpoint.com, etc.
- Enterprise Applications such as banking applications.
- Mobile
- Embedded System
- Smart Card
- Robotics
- Games, etc.
Types of Java Applications
Standalone application are Media player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.
Application that runs on the server side and creates a dynamic page is called a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc.
This technologies are used for creating web applications in Java.
Such as banking applications, etc. is called an enterprise application. It has advantages like high-level security, load balancing, and clustering. In Java,
EJB is used for creating enterprise applications.
An application which is created for mobile devices is called a mobile application.
Currently, Android and Java ME are used for creating mobile applications.
Application that runs on the server side and creates a dynamic page is called a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc.
This technologies are used for creating web applications in Java.
Such as banking applications, etc. is called an enterprise application. It has advantages like high-level security, load balancing, and clustering. In Java,
EJB is used for creating enterprise applications.
An application which is created for mobile devices is called a mobile application.
Currently, Android and Java ME are used for creating mobile applications.
Java Platforms / Editions
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String
, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.
It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String
, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.2) Java EE (Java Enterprise Edition)
It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built on top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA
, etc.
It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built on top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA
, etc.3) Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.
It is a micro platform that is dedicated to mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.
- What is the difference between JRE and JVM?
- What is the purpose of JIT compiler?
- Can we save the java source file without any name?
- Why java uses the concept of Unicode system?
Principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic".
Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of espresso bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office.
It is used to develop rich internet applications. It uses a lightweight user interface API.
- What is the difference between JRE and JVM?
- What is the purpose of JIT compiler?
- Can we save the java source file without any name?
- Why java uses the concept of Unicode system?
Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of espresso bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office.
Features of Java
Invalid Java main() method signature
What happens at runtime?
At runtime, the following steps are performed:

---------------------------------------------------------------------------------------------------------------------
Comparator VS comparable interfaces
(Comparable Interface --> compareTo)
package collectionPractice;
public class ComparableExample implements Comparable<ComparableExample>{
//defining constraints
private int wheels;
private int model;
private String name;
//Creating getters & Setters
public int getWheels() {
return wheels;
}
public void setWheels(int wheels) {
this.wheels = wheels;
}
public int getModel() {
return model;
}
public void setModel(int model) {
this.model = model;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//defining toString method
@Override
public String
toString() {
return "ComparableExample{" +
"wheels=" + wheels +
", model=" + model +
", name='" + name + '\'' +
'}';
}
//Override the compareTo method
@Override
public int compareTo(ComparableExample carTest) {
if(this.getWheels() > carTest.getWheels()) return 1;
else if(this.getWheels() < carTest.getWheels()) return -1;
return 0;
}
}
class Test{
public static void main(String[] args) {
ComparableExample comparableExample2 = new ComparableExample(3,2021,"DEEP");
int result = comparableExample2.compareTo(new ComparableExample(4,2017,"BMW"));
System.out.println(result);
}
}
Comparator:- We prefer to use this interface as it supports open for extension but close for modification principal.
In this given example we have created a BikeTestComparator class that will be compare with the list of bike's years.
package collectionPractice;
public class BikeTestComparator {
private int year;
private String model;
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public BikeTestComparator(int year, String model) {
this.year = year;
this.model = model;
}
@Override
public String toString() {
return "BikeTestComparator{" +
"year=" + year +
", model='" + model + '\'' +
'}';
}
}
package collectionPractice;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ComparatorExample implements Comparator<BikeTestComparator>
{
@Override
public int compare(BikeTestComparator o1, BikeTestComparator o2) {
if(o1.getYear() > o2.getYear()) return 1;
else if(o1.getYear() < o2.getYear()) return -1;
return 0;
}
public static void main(String[] args) {
ArrayList<BikeTestComparator> bikeList = new ArrayList<>();
bikeList.add(new BikeTestComparator(2017,"BMW"));
bikeList.add(new BikeTestComparator(2028,"TVS"));
bikeList.add(new BikeTestComparator(2019,"Honda"));
bikeList.add(new BikeTestComparator(2025,"Mercedes"));
Collections.sort(bikeList,new ComparatorExample());
for(BikeTestComparator bikes : bikeList){
System.out.println(bikes);
}
}
}
Interface VS Abstract class
Interface- SAM interface - single abstract method
Access modifiers
- abstract- Modifier 'abstract' is redundant for interfaces
- private & Protected- Not allowed
- public & default- ALLOWED
public interface InterFacePractice { }
interface InterFacePractice { }
Constraints Modifiers
- Only default with intialisation
int d =0;
String de=null;
Methods
void deepesh() {
}
default void deepesh()
{
}
private void deepesh() {
}
Public and Abstract:- Modifier 'abstract' is redundant for interface methods
void deepesh();
Comments
Post a Comment