Default and Static methods in Interface
- Till JDK1.7, the interface will contain only abstract method and public static final variables
- From JDK1.8 onwards apart from abstract method, the interface can also contain default and static method
- why default method?
without affecting the implemented classes, if we want to add any new methods inside the interface then we can go for default method
- why static method?
If my functionality is no way related to the class (ie) static method, instead of defining inside the class we can define inside the interface and access it using "interfacename.methodname"
- From JDK1.9 onwards, the interface can also contain private and private static methods, if we have common functionalities inside default method and to avoid duplication of code, we can define those common functionalities inside private mthod and access it whenever it is needed inside default method
interface A {
default void show() {
System.out.println("Inside A's show method");
}
}
interface B {
default void show() {
System.out.println("Inside B's show method");
}
}
class C implements A,B {
@Override
public void show() {
A.super.show();
B.super.show();
}
}
public class Main {
public static void main(String...args) {
C c=new C();
c.show();
}
}
Interface access members
1. Accessible from default and private methods within interface
constant variable = yes
abstract method = yes
another default method = yes
private method=yes
static method = yes
private static method=yes
2. Accessible from static methods within interface
constant variable = yes
abstract method = NO
another default method = NO
private method=NO
static method = yes
private static method=yes
3. Accessible from instance method by implementing the interface
constant variable = yes
abstract method = yes
default method = yes
private method=NO
static method = yes
private static method=no
4. Accessible outside interface without implementing the interface
constant variable = yes
abstract method = no
default method = no
private method=NO
static method = yes
private static method=no
interface MyInterface {
//Till JDK1.7
/*public static final*/ int CONSTANT=0;
/*public abstract*/ int abstractMethod();
//From JDK1.8
/*public*/ default int defaultMethod() {
abstractMethod();
staticMethod();
privateMethod();
privateStaticMethod() ;
return CONSTANT;
}
/*public*/ static int staticMethod() {
staticMethod();
privateStaticMethod();
return CONSTANT;
}
//From JDK1.9
private int privateMethod() {
abstractMethod();
staticMethod();
privateStaticMethod();
defaultMethod();
return CONSTANT;
}
private static int privateStaticMethod() {
staticMethod();
return CONSTANT;
}
}
class Sample implements MyInterface {
@Override
public int abstractMethod() {
defaultMethod();
MyInterface.staticMethod();
return CONSTANT;
}
}
class Sample1 {
public int instanceMethod() {
MyInterface.staticMethod();
return MyInterface.CONSTANT;
}
}
public class Main {
public static void main(String...args) {
}
}
var keyword
- Available from JDK10
- used to infer the datatype at runtime based on the value
int a=10;
var a1="hello"; //String
var a2=3.13; //double
var a3=2.14f; //float
- used only inside methods, constructors, compound/instance block and loops
Rules
1. var cant declare without initial value
2. var can be declared in first line and initialized in second line
3. var cannot be initialized with null value without the type
4. var is not permitted in multiple variable declaration
5. var cannot be used to initialize an array
6. var is a reserved type but not keyword, so we can use var as an identifier except for class, interface and enum
7. var in lambda expr, but you cant mix var and non var parameters
/*class var { //error
}
interface var { //error
}
enum var{ //error
}*/
class Var {
Var() {
var var="var"; //correct
}
public void var() { //correct
Var var=new Var();
}
/*public void var(var v) { //error, parameter type cant be var
Var var=new Var();
}*/
}
interface Operation1 {
void add(int a,int b);
}
public class Main {
Main() {
var a1=10;
}
{ //compound block
var a2="hello";
}
public static void main(String...args) {
var c=3.14;
for(var i=0;i<5;i++) {
System.out.println(i);
}
// var c1; //error
var c1=2;
var x
=3;
//var x1=null; //error
var x1="hello";
x1=null;
var x2=(String) null;
int a=10,b=20;
//var y1=10,y2=20; //error
//var y1[]= {1,2,3}; //error
Operation1 m1=(var x11,var x21) -> System.out.println(x11+x21); //correct
Operation1 m2=(var x11,int x21) -> System.out.println(x11+x21); //error
}
}
J2SE - Java 2 Standard Edition - develop system/networking project
J2EE - Java 2 Enterprise Edition - develop web oriented appl
J2ME - Java 2 Micro/Mobile Edition
J2EE - Java 2 Enterprise Edition - develop web oriented appl - traditional approach
J2EE Components - 3 components
1. JSP(Java Server Pages) - HTML + Java - used to create dynamic web pages
2. Servlet - java prg used to write business logic
3. EJB(Enterprise Java Bean)- EJB2.X/EJB3.X - used to develop enterprise appl - 3 types
1. Session bean - write business logic
2. Entity bean - persist data into db
3. Message Driven bean - send sync and async message between servers
Problems with traditional approach
1. J2EE applications tend to contain excessive amounts of "plumbing" code -> Thers would always be a high proportion of code that doesn't do anything: JNDI lookup code, Transfer Objects, try/catch blocks to acquire and release JDBC resources. Writing and maintaining such plumbing code proves a major drain on resources that should be focused on the application's business domain.
2. J2EE applications are hard to unit test -> The J2EE APIs, especially, the EJB component model, does not take into account ease of unit testing. It is very difficult to test applications based on EJB and many other J2EE APIs outside an application server.
3. Certain J2EE technologies have failed in performance. EJB 2.x, for instance -> The main offender here is entity beans, which have proven little short of disastrous for productivity.
J2EE Frameworks
There are many frameworks which claim to resolve the issues mentioned earlier. For instance, Struts.
Struts is a web framework which works on the web tier(client part) and helps us achieve MVC and is doing pretty well in the market. However Spring takes over struts in that it is not just a web framework but an application framework(develop entire appl (ie) client+server+database)
Unlike single-tier frameworks such as Struts(web part) or Hibernate(db part), Spring aims to help structure whole applications in a consistent, productive manner. It has 7 modules that offer services for use throughout an application.
The essence of Spring is in providing enterprise services to Plain Old Java Objects (POJOs). This is valuable in a J2EE environment.
Spring framework(7.x)
- open source, used to develop both standalone(Java based) and web appl
- It is a framework, so we have to download all jar files and put inside appl
Features
1. Reduce glue code/plumbing work
Spring Framework takes lot of load off the programmer by providing dependencies when required and by using AOP(Aspect Oriented Programming) - define cross cutting functionality(common functionality like security, transaction, logging, exception handling etc) in single place and access it whenever it is needed using Aspect
2. Externalize dependencies - Inversion of Control(IOC) - Dependency Injection
Dependencies are described in a separate file (xml) rather than mixing it with the business logic code itself. This gives a better control over the application.
- Loosely coupled appl - inject the value at runtime in separate xml file
class Person {
Integer id;
String name;
Address address;
}
Address a =new Address();
Person p=new Person(); //tightly coupled appl
p.id=1;
p.name="Ram";
p.address=a;
3. Manage dependencies at a single place - all bean prg is configured in single xml file
Dependencies can be managed better due to this.
4. Improve testability
Actual code can easily be replaced by a stub for testing purposes.
5. Foster good application design
Since the actual implementation sits behind the interfaces, it fosters good application design.
6. Flexibility
Spring offers integration points with several other frameworks. So, you do not have to write them yourself.
7 modules
1. Spring core module
- Support only IOC feature
- Using BeanFactory interface
2. Spring Context module
- Support IOC feature + support internationalization, lifecycle events, remoting, scheduling, email, integrate with Velocity, FreeMarker, EJB etc
- Using ApplicationContext interface
3. Spring AOP(Aspect Oriented Programming) module
- define cross cutting functionality(common functionality like security, transaction, logging, exception handling etc) in single place and access it whenever it is needed using Aspect
4. Spring DAO(Data Access Object) module
- Spring itself provides inbuilt interface and classes to communicate with db like JdbcTemplate, RowMapper etc
5. Spring ORM(Object Relational Mapping) module
- used to integrate Spring with ORM frameworks like Hibernate, iBatis, JDO, Toplink
6. Spring webflow module
- used to integrate Spring with Struts framework
7. Spring MVC module
- used to develop web tier based on MVC architecture using Spring itself
Inversion of Control(IOC)
Dependency Injection
- Objects are given their dependencies at runtime in separate xml file
3 types
1. Setter injection - Spring
- dependencies are configured through beans setter method for their properties by using <property> tag in xml file
2. Constructor injection - Spring
- dependencies are configured through beans constructor for their properties by using <constructor-arg> tag in xml file
3. Interface injection - Avalon
- dependencies are configured through beans interface for their properties
Spring IOC container - 2 types of container to perform DI
1. BeanFactory interface
- org.springframework.beans.factory.* package
- It is lazy loading
- used to create and destroy the bean
- Uses XmlBeanFactory(Resource) class - used to load all beans defined in xml file
- Object getBean(String)/Object getBean(Object) - used to instantiate the bean at runtime and performs DI
2. ApplicationContext interface
- org.springframework.context.* package
- It is eager loading
- used to create and destroy the bean
- 3 classes
1. ClassPathXmlApplicationContext(String xmlfile) - loads xml file present in classpath (ie) in src folder
2. FileSystemXmlApplicationContext(String xmlfile) - loads xml file present in filesystem (ie) in project folder or c:/ or d:/
3. WebXmlApplicationContext(String xmlfile) - loads xml file from web.xml
3 program
1. Bean prg - simple POJO class that contains getter and setter
2. xml file - configure bean prg in xml file to perform DI
3. main prg
Apache maven
- It is project development tool, instead of downloading jar file manually, maven will download all jar files from internet on behalf of user
- pom(project object model).xml - we have to provide related dependency
- 2 repository
1. Remote repository - for first time alone maven will download all jar files remotely present in internet and put in local repo
2. Local repository - maven will internally create a repo locally in ur machine (ie) C:\Users\urname\.m2
1. Download apache maven
apache-maven-3.9.11-bin.zip
2. Extract zip file
3. Set env variables
In search - Type "env" - Select "Edit env variables for ur account" - Click "New" in user variablle
Variable name: MAVEN_HOME
Variable value: C:\Softwares\apache-maven-3.6.3
click ok
- Select Path - Click Edit - Click New - Paste "C:\Softwares\apache-maven-3.6.3\bin"
Click ok
Click ok
4. Open cmd prompt
C:\Users\senthil.kumart>mvn --version
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: C:\Softwares\apache-maven-3.6.3\bin\..
Java version: 21.0.2, vendor: Oracle Corporation, runtime: C:\Softwares\openjdk-21.0.2_windows-x64_bin\jdk-21.0.2
Default locale: en_US, platform encoding: UTF-8
OS name: "windows 11", version: "10.0", arch: "amd64", family: "windows"
It will create local repo in ur machine
Handson
Given list of employees
List<Employee> employees = Arrays.asList(
new Employee(101, "Roopa", "IT", 65000, LocalDate.of(2021, 5, 10)),
new Employee(102, "Senthil", "HR", 45000, LocalDate.of(2018, 1, 20)),
new Employee(103, "Arun", "Finance", 55000, LocalDate.of(2022, 7, 5)),
new Employee(104, "Kumar", "IT", 75000, LocalDate.of(2019, 3, 14)),
new Employee(105, "Priya", "Finance", 60000, LocalDate.of(2020, 9, 25))
);
1. Find Employees who joined after 2020
2. Sort employees by salary using Lambda
3. Group employees by department
4. Get average salary of all employees
5. Find highest paid employee
6. Calculate years of experience using Date API
7. Create a comma-separated string of all employee names
8. Find Employees earning more than 60,000
No comments:
Post a Comment