Se ha denunciado esta presentación.
Se está descargando tu SlideShare. ×

Core Java Tutorials by Mahika Tutorials

Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio

Eche un vistazo a continuación

1 de 122 Anuncio

Core Java Tutorials by Mahika Tutorials

Descargar para leer sin conexión

Mahika Tutorials sharing PPT slide for core java programming language. Go threw this slide and visit our YouTube page too
https://www.youtube.com/c/mahikatutorials

Mahika Tutorials sharing PPT slide for core java programming language. Go threw this slide and visit our YouTube page too
https://www.youtube.com/c/mahikatutorials

Anuncio
Anuncio

Más Contenido Relacionado

Presentaciones para usted (20)

Similares a Core Java Tutorials by Mahika Tutorials (20)

Anuncio

Más reciente (20)

Core Java Tutorials by Mahika Tutorials

  1. 1. checked exception Core Java
  2. 2. mahika.a.motwani@gmail.com Programming Languages High Level Languages (Machine independent) Low-Level Languages (Machine dependent) Assembly language Machine(Binary) language
  3. 3. Java  Java was created by James Gosling at Sun Microsystems (which is now acquired by Oracle Corporation) and released in 1995.  Java is a high level, object-oriented programming language.
  4. 4. OOPs Concepts
  5. 5. Encapsulation Binding (or wrapping) code and data together into a single unit. A java class is the example of encapsulation.
  6. 6. Abstraction Hiding internal details and showing functionality only. With Abstraction WithoutAbstraction
  7. 7. Inheritance A mechanism by which a class acquires all the properties and behaviours of an existing class. Provides code reusability. Used to achieve runtime polymorphism.
  8. 8. Polymorphism Ability to take multiple forms. Example- int a=10,b=20,c; c=a+b; //addition String firstname=“Sachin”, lastname=“Tendulkar”, fullname; fullname=firstname+lastname;//concatenation
  9. 9. OOPLs (Four OOPs features) Partial OOPL Pure OOPLFully OOPL Classes not mandatory. Data members and methods can be given outside class. e.g. C++ Classes mandatory. Data members and methods cannot be given outside class. e.g. Java Classes mandatory. Data members and methods cannot be given outside class. Primitive data types not supported. e.g. Smalltalk Java supports primitive data types , hence it is a fully OOPL but not pure OOPL. int i=20; //primitive type Integer a=new Integer(20); //Class type
  10. 10. Core Java
  11. 11. Signature of main()
  12. 12. public static void main(String[] args) { ………….. ………….. }
  13. 13. returnType methodName(arguments) { …… } void m1() { ….. ….. } int m2() { ….. return 2; } int m3(int n) { ….. return n*n; }
  14. 14. public static void main(String[] args) { ………….. ………….. }
  15. 15. class Test { public static void myStatic() { ----- ----- ----- } public void myNonStatic() { ----- } } class Sample { public void CallerFunction() { // Invoking static function Test.myStatic(); // Invoking non-static function Test t= new Test(); t.myNonStatic(); } } Invoking Member Funtions Of A Class
  16. 16. class Test { public static void main(String[] args) { ----- ----- ----- } } // Incase of static main() Test.main(); Invoking main() Since the main method is static Java virtual Machine can call it without creating any instance of a class which contains the main method. // Incase of non-static main() Test t=new Test() t.main();
  17. 17. Thank You
  18. 18. Java Code (.java) JAVAC Compiler Byte Code (.class) JVM JVM JVM Linux Mac Windows
  19. 19. JVM JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed. JVM is the engine that drives the java code The JVM performs following main tasks:  Loads code  Verifies code  Executes code
  20. 20. JRE  JRE is an acronym for Java Runtime Environment. JRE JVM Llibraries like rt.jar Other files
  21. 21. JRE JVM Llibraries like rt.jar Other files Development tools like javac, java etc. JDK JDK JDK is an acronym for Java Development Kit. Includes a complete JRE (Java Runtime Environment) plus tools for developing, debugging, and monitoring Java applications.
  22. 22. Internal Architecture of JVM Java Runtime System Class Loader Class Area Heap Stack PC Register Native Method Stack Execution engine Native Method Interface Java Native Libraries Memory areas allocated by JVM
  23. 23. Internal Architecture of JVM Java Runtime System Class Loader Class Area Heap Stack PC Register Native Method Stack Execution engine Native Method Interface Java Native Libraries Memory areas allocated by JVM
  24. 24. Java Keywords Words that cannot be used as identifiers in programs. There are 50 java keywords. All keywords are in lower-case. Each keyword has special meaning for the compiler. Keywords that are not used in Java so far are called reserved words.
  25. 25. Category Keywords Access modifiers private, protected, public Class, method, variable modifiers abstract, class, extends, final, implements, interface, native,new, static, strictfp, synchronized, transient, volatile Flow control break, case, continue, default, do, else, for, if, instanceof,return, switch, while Package control import, package Primitive types boolean, byte, char, double, float, int, long, short Exception handling assert, catch, finally, throw, throws, try Enumeration enum Others super, this, void Unused const, goto Points to remember  const and goto are resevered words.  true, false and null are literals, not keywords. List of Java Keywords
  26. 26. Rules for Naming Java Identifiers Allowed characters for identifiers are[A-Z], [a-z],[0-9], ‘$‘(dollar sign) and ‘_‘ (underscore). Should not start with digits(0-9). Case-sensitive, like id and ID are different. Java keyword cannot be used as an identifier. Java Identifiers Names given to programming elements like variables, methods, classes, packages and interfaces.
  27. 27. Java Naming conventions Name Convention class name should start with uppercase letter and be a noun e.g.Shape, String, Color, System, Thread etc. interface name should start with uppercase letter and be an adjective e.g. Runnable, Clonable etc. method name should start with lowercase letter and be a verb e.g. compute(), print(), println() etc. variable name should start with lowercase letter e.g. firstName, lastName etc. package name should be in lowercase letter e.g. java, lang, sql, util etc. constants name should be in uppercase letter. e.g. BLUE, MAX_PRIORITY etc.
  28. 28. Core Java
  29. 29. Class  A template that describes the data and behavior. Object An entity that has state and behavior is known as an object e.g. chair, bike, table, car etc. state: represents data (value) of an object. behavior: represents the functionality of an object such as deposit, withdraw etc.
  30. 30. Student Data members id name Methods setId() setName() getId() getName() class
  31. 31. public class Student { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Java class example
  32. 32. Instantiation/ Object Creation- Classname referenceVariable=new Classname(); e.g.- Student s=new Student(); Method Invocation/Call- Non-static method: referenceVariable.methodname(); e.g.- s.show(); static method: Classname.methodname(); e.g.- Sample.display();
  33. 33. Scanner class A class in java.util package Used for obtaining the input of the primitive types like int, double etc. and strings Breaks its input into tokens using a delimiter pattern, which by default matches whitespace. To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file.
  34. 34. Creating instance of Scanner class To read from System.in: Scanner sc = new Scanner(System.in); To read from File: Scanner sc = new Scanner(new File("myFile"));
  35. 35. Commonly used methods of Scanner class Method Description public String next() it returns the next token from the scanner. public byte nextByte() it scans the next token as a byte. public short nextShort() it scans the next token as a short value. public int nextInt() it scans the next token as an int value. public long nextLong() it scans the next token as a long value. public float nextFloat() it scans the next token as a float value. public double nextDouble() it scans the next token as a double value.
  36. 36. Thank You
  37. 37. Types of Variable local instance static
  38. 38. public class Student { int rn; //instance variable String name; //instance variable static String college; //static variable void m1() { int l; //local variable …… } ………. }
  39. 39. id=1 name= Hriday Stack Heap id=2 name= Anil s1 s2 college=“SVC”” Class Area class Student{ int id; String name; static String college=“SVC”; ……… public static void main(String args[]){ Student s1=new Student(); Student s2=new Student(); ………… } }
  40. 40. Thank You
  41. 41. Data Type Default Value Default size boolean false 1 bit char 'u0000' 2 byte byte 0 1 byte short 0 2 byte int 0 4 byte long 0L 8 byte float 0.0f 4 byte double 0.0d 8 byte lowest unicode value:u0000 highest unicode value:uFFFF
  42. 42. Control Structures 1. Conditional a) Simple if b) if–else c) if-else-if ladder d) Nested if e) switch case 2. Looping a) while loop b) for loop c) do while loop d) for each/enhanced for loop
  43. 43. if Statement: if(condition){ //code to be executed }
  44. 44. if –else Statement: if(condition){ //code if condition is true } else{ //code if condition is false }
  45. 45. if-else-if ladder Statement if(condition1){ //code to be executed if condition1 is true } else if(condition2){ //code to be executed if condition2 is true } else if(condition3){ //code to be executed if condition3 is true } ... else{ //code to be executed if all the conditions are false } Test Expression 1 Test Expression 2 Test Expression 3 No No No Statement 1 Statement 2 Statement 3 else Body Yes Yes Yes
  46. 46. if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true if(Boolean_expression 2) { // Executes when the Boolean expression 2 is true } } Nested if
  47. 47. Core Java
  48. 48. switch Statement switch(expression){ case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional ...... default: //code to be executed if all cases are not matched; } Expression case 1? case 2? case 3? No No No Case Block 1 Case Block 2 Case Block 3 default Block Yes Yes Yes
  49. 49. switch Statement Expression can be byte, short, char, and int. From JDK7 onwards, it also works with enumerated types ( Enums in java), the String class and Wrapper classes. Duplicate case values are not allowed. switch(ch) { case 1: ....... break; case 1: ...... break; ………… }
  50. 50. The value for a case must be the same data type as the variable in the switch. switch(ch) { case 1: ...... break; case 2: ...... break; } The value for a case must be a constant or a literal.Variables are not allowed.
  51. 51. The break statement is used inside the switch to terminate a statement sequence. The break statement is optional. If omitted, execution will continue on into the next case. The default statement is optional.
  52. 52. while Loop while(condition){ //code to be executed }
  53. 53. do-while Loop do{ //code to be executed }while(condition);
  54. 54. for Loop for(initialization;condition;incr/decr){ //code to be executed }
  55. 55. break Statement Used to break loop or switch statement.
  56. 56. continue Statement Used to continue loop. Skips the remaining code at specified condition.
  57. 57. Polymorphism Run-time PolymorphismCompile-time Polymorphism Method OverridingMethod Overloading
  58. 58. Method Overloading When a class have multiple methods by same name but different parameters. Advantage : Increases the readability of the program. Different ways to overload the method: 1) By changing number of arguments 2) By changing the data type of arguments Method Overloading is not possible by changing the return type or access specifier of a method.
  59. 59. Method Overloading and Type Promotion
  60. 60.  If we have overloaded methods with one byte/short/int/long parameter then always method with int is called.  To invoke method with long parameter L should be append to the value while calling  Method with byte/short is called only if we pass the variable of that type or we typecast the value.  If we have overloaded method with one int/float/double and we pass long value then method with int parameter is called.  If we have overloaded method with one float/double and we pass long value then method with float parameter is called.
  61. 61. Ambiguity in Method Overloading class Test{ void sum(int a,long b){System.out.println(a+b);} void sum(long a,int b){System.out.println(a+b);} public static void main(String args[]){ Test obj=new Test(); obj.sum(20,20);// ambiguity } } Output:Compile Time Error
  62. 62. Constructor  Special type of method that is used to initialize the object.  Invoked at the time of object creation.  Can be overloaded. Rules for creating java constructor:  Constructor name must be same as its class name  Constructor must have no explicit return type Types of java constructors:  Default constructor (no-arg constructor)  Parameterized constructor
  63. 63. If there is no constructor in a class, compiler automatically creates a default constructor. class Student{ } class Student{ Student() { } } compiler Student.java Student.class
  64. 64. Java Copy Constructor There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++. There are many ways to copy the values of one object into another in java. They are:  By constructor  By assigning the values of one object into another  By clone() method of Object class
  65. 65. static keyword static is a non-access modifier. Used for memory management mainly.  The static can be: variable (also known as class variable) method (also known as class method) block nested class
  66. 66. static variable Used to refer the common property of all objects e.g. company name of employees,college name of students etc. Gets memory only once in class area at the time of class loading. Local variables cannot be static. Advantage : It makes your program memory efficient (i.e it saves memory).
  67. 67. //Program for static variable class Student{ int id; String name; static String college =“SVC"; Student(int i,String n){ id=i; name = n; } void display (){ System.out.println(id+" "+name+" "+college);} public static void main(String args[]){ Student s1 = new Student(1,“Hriday"); Student s2 = new Student(2,“Anil"); s1.display(); s2.display(); } } id=1 name= “Hriday” Stack Heap id=2 name= “Anil” s1 s2 college=“SVC”” Class Area
  68. 68. static method Method defined with the static keyword.  Belongs to the class rather than object of a class.  Can be invoked without the need for creating an instance of a class.  Can access static data members and can change the value of it.  Cannot use non static data member or call non-static method directly.  this and super cannot be used in static context.
  69. 69. static block Used to initialize the static data member.  Is executed before main method at the time of classloading. Example : class A{ static{ System.out.println("static block invoked"); } public static void main(String args[]){ System.out.println(“main invoked"); } }
  70. 70. this keyword in java A reference variable that refers to the current object. Usage of this keyword : this keyword can be used to refer current class instance variable. this() can be used to invoke current class constructor. this can be used to invoke current class method (implicitly) this can be used to return the current class instance from the method. this can be passed as an argument in the method call. this can be passed as argument in the constructor call.
  71. 71. this() : to invoke current class constructor Used for constructor chaining. Used to reuse the constructor. Call to this() must be the first statement in constructor. Syntax this(); // call default constructor this(value1,value2,.....) //call parametrized constructor
  72. 72. //this() : to invoke current class constructor public class Rectangle { private int x, y; private int width, height; public Rectangle() { this(0, 0, 0, 0); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } ………. }
  73. 73. this :to invoke current class method (implicitly) Can be used to invoke method of the current class. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. class Test{ void m1( ) { …. } void m2( ) { m1() } …. } class Test{ void m1( ) { …. } void m2( ) { this.m1() } …. } compiler Test.java Test.class
  74. 74. this: to pass as an argument in the method class Test { int a; int b; Test() { a = 40; b = 60; } // Method that receives 'this' keyword as parameter void display(Test obj) { System.out.println("a = " + a + " b = " + b); } // Method that pases current class instance void get() { display(this); } public static void main(String[] args) { Test object = new Test(); object.get(); } } Output:- a=40 b=60
  75. 75. Core Java
  76. 76. mahika.tutorials@gmail.com this: to pass as argument in the constructor call class B{ A obj; B(A obj) { this.obj=obj; } void display(){ System.out.println(obj.data); //10 } } class A{ int data=10; A() { B b=new B(this); b.display(); } public static void main(String args[]){ A a=new A(); } }
  77. 77. this keyword in java A reference variable that refers to the current object. Usage of this keyword :  this keyword can be used to refer current class instance variable.  this() can be used to invoke current class constructor.  this can be used to invoke current class method (implicitly)  this can be used to return the current class instance from the method.  this can be passed as an argument in the method call.  this can be passed as argument in the constructor call. this keyword cannot be used in static context.
  78. 78. Inheritance  A mechanism in which one object acquires all the properties and behaviors of parent object.  Represents the IS-A relationship, also known as parent-child relationship  extends keyword indicates that you are making a new class that derives from an existing class.  The meaning of "extends" is to increase the functionality.  A class which is inherited is called parent or super class and the new class is called child or subclass. Inheritance in java is used:  For Method Overriding (so runtime polymorphism can be achieved).  For Code Reusability. Syntax of Java Inheritance: class Subclass-name extends Superclass-name { //methods and fields }
  79. 79. Types of inheritance in java Multiple inheritance is not supported in java through class
  80. 80. Object class is the superclass of all the classes in java by default. Every class in Java is directly or indirectly derived from the Object class. Object class is present in java.lang package. class A { …….. } class A extends Object { …….. } Object class
  81. 81. class A { ……. } class B extends A { ……. } class A extends Object { …….. } class B extends A { ……. } Object class
  82. 82. Commonly used Methods of Object class: Method Description public boolean equals(Object obj) compares the given object to this object. protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object. public String toString() returns the string representation of this object. public final void notify() wakes up single thread, waiting on this object's monitor. public final void notifyAll() wakes up all the threads, waiting on this object's monitor. public final void wait(long timeout)throws InterruptedException causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method). protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage collected.
  83. 83. Account SavingAccount Single Inheritance Account • String accountId • double accountBalance SavingAccount • double interestRate • double minimumBalance
  84. 84. Account SavingAccount SilverSavingAccount Multilevel Inheritance Account • String accountId • double acctBalance SavingAccount • double interestRate • double minimumBalance SilverSavingAcccount • String specialOfferId
  85. 85. Account SavingAccount CurrentAccount Hierarchical Inheritance Account • String accountId • double acctBalance SavingAccount • double interestRate • double minimumBalance CurrentAccount • double transactionFee;
  86. 86. mahika.a.motwani@gmail.com Multiple Inheritance A feature where a class can inherit properties of more than one parent class. Java doesn’t allow multiple inheritance by using classes ,for simplicity and to avoid the ambiguity caused by it. It creates problem during various operations like casting, constructor chaining etc.
  87. 87. mahika.a.motwani@gmail.com Multiple Inheritance and Ambiguity class A { void show() { System.out.println("Hello");} } class B { void show() { System.out.println("Welcome"); } } class C extends A,B //suppose if it was allowed { public static void main(String args[]) { C obj=new C(); obj.show(); //ambiguity } }
  88. 88. mahika.a.motwani@gmail.com Multiple Inheritance and Diamond Problem
  89. 89. mahika.a.motwani@gmail.com Multiple inheritance in Java by interface If a class implements multiple interfaces, or an interface extends multiple interfaces.
  90. 90. Polymorphism Run-time PolymorphismCompile-time Polymorphism Method OverridingMethod Overloading
  91. 91. Method Overriding If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. Usage :  Used to provide specific implementation of a method that is already provided by its super class.  Used for runtime polymorphism class Vehicle{ void run(){System.out.println("Vehicle is running");} } class Bike extends Vehicle{ void run(){System.out.println("Bike is running ”);} public static void main(String args[]){ Bike obj = new Bike(); obj.run(); } Example:
  92. 92. class Shape{ void draw() { System.out.println("No Shape"); } } class Rectangle extends Shape{ void draw() { System.out.println("Drawing rectangle"); } } class Circle extends Shape{ void draw() { System.out.println("Drawing circle"); } } class Triangle extends Shape{ void draw() { System.out.println("Drawing circle"); } } public class Test{ public static void main(String args[]){ Shape s; s=new Shape(); s.draw(); s =new Circle(); s.draw(); s=new Rectangle(); s.draw(); s=new Triangle(); s.draw(); } } At compile-time:
  93. 93. class Shape{ void draw() { System.out.println("No Shape"); } } class Circle extends Shape{ void draw() { System.out.println("Drawing circle"); } } class Rectangle extends Shape{ void draw() { System.out.println("Drawing rectangle"); } } class Triangle extends Shape{ void draw() { System.out.println("Drawing circle"); } } public class Test{ public static void main(String args[]){ Shape s; s=new Shape(); s.draw(); s =new Circle(); s.draw(); s=new Rectangle(); s.draw(); s=new Triangle(); s.draw(); } } At run-time:
  94. 94. Rules for Method Overriding:  Method must have same name as in the parent class  Method must have same parameter as in the parent class.  Method must have same return type(or sub-type).  Must be IS-A relationship (inheritance).  private method cannot be overridden.  final method cannot be overridden  static method cannot be overridden because static method is bound with class whereas instance method is bound with object.  We can not override constructor as parent and child class can never have constructor with same name.  Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class.  Binding of overridden methods happen at runtime which is known as dynamic binding.
  95. 95. ExceptionHandling with MethodOverriding in Java  If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception. class Child extends Parent{ void msg()throws IOException { System.out.println(“child"); } public static void main(String args[]) { Parent p=new Child(); p.msg(); } } class Parent{ void msg() { System.out.println("parent"); } } Output:Compile Time Error
  96. 96.  If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception. class Parent{ void msg() { System.out.println("parent"); } } class Child extends Parent{ void msg()throws ArithmeticException { System.out.println("child"); } public static void main(String args[]) { Parent p=new Child(); p.msg(); } } Output:child
  97. 97.  If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. class Child extends Parent{ void msg()throws Exception { System.out.println("child"); } public static void main(String args[]) { Parent p=new Child(); try{ p.msg(); }catch(Exception e){ } } } class Parent{ void msg()throws ArithmeticException{ System.out.println("parent"); } } Output:Compile Time Error
  98. 98. class Parent{ void msg()throws Exception{ System.out.println("parent"); } } Class Child extends Parent{ void msg()throws ArithmeticException{ System.out.println("child"); } public static void main(String args[]){ Parent p=new Child(); try{ p.msg(); }catch(Exception e){} } } Example in case subclass overridden method declares subclass exception Output:child
  99. 99. Covariant Return Type Specifies that the return type may vary in the same direction as the subclass. Since Java5, it is possible to override method by changing the return type if subclass overrides any method, but it changes its return type to subclass type. class ShapeFactory { public Shape newShape() { ………… } } class CircleFactory extends ShapeFactory { public Circle newShape() { …… } } class Shape { ……… } class Circle extends Shape { ……… }
  100. 100. super keyword A reference variable that is used to refer immediate parent class object. super keyword cannot be used in static context. Usage :  super is used to refer immediate parent class instance variable.  super() is used to invoke immediate parent class constructor,.  super is used to invoke immediate parent class method.
  101. 101. super used to refer immediate parent class instance variable: class Vehicle{ int speed=70; } class Bike extends Vehicle{ int speed=100; void display(){ System.out.println(super.speed);// Vehicle speed System.out.println(speed);// Bike speed } public static void main(String args[]){ Bike b=new Bike(); b.display(); } }
  102. 102. super() to invoke parent class constructor: class Vehicle{ Vehicle(){System.out.println("Vehicle created");} } class Bike extends Vehicle{ Bike(){ super();//invokes parent class constructor System.out.println("Bike created"); } public static void main(String args[]){ Bike b=new Bike(); } }
  103. 103.  If used, super() must be the first statement inside the constructor, hence either super() or this() can be used inside the constructor.  super() is added in each class constructor automatically by compiler if there is no super() or this(). class Bike{ Bike() { } } class Bike{ Bike() { super(); } } compiler Bike.java Bike .classa super() :to invoke parent class constructor
  104. 104. super used to invoke parent class method: class Vehicle{ void show(){System.out.println("Vehicle Runing");} } class Bike extends Vehicle{ void show(){System.out.println("Bike Runing "); } void display(){ super.show(); show(); } public static void main(String args[]){ Bike b=new Bike(); b.display(); } }
  105. 105. final Keyword Used to restrict the user. final can be: 1) VariableIf you make any variable as final, you cannot change the value of final variable(It will be constant). 2) Method->If you make any methode as final, you cannot override it. 3) Class->If you make any class as final, you cannot extend it.
  106. 106.  final method is inherited but you cannot override it.  A final variable that is not initialized at the time of declaration is known as blank final variable.  We can initialize blank final variable only in constructor. For example: class Test{ final int i;//blank final variable Test(){ i=80; ...... } }  If a method is declared private and final in superclass then we can have method with the same signature in subclass also because private is not inherited.  Constructor cannot be declared as final because constructor is never inherited. final Keyword
  107. 107. Core Java
  108. 108. Java Package Group of similar types of classes, interfaces and sub-packages. Types: built-in package (such as java, lang, io, util, sql etc.) user-defined package. Advantages:  Used to categorize the classes and interfaces so that they can be easily maintained.  Provides access protection.  Removes naming collision.
  109. 109. Ways to access the package from outside the package: 1) import packageName.*; 2) import packageName.classname; 3) fully qualified name. If you import a package, subpackages will not be imported.
  110. 110. Core Java
  111. 111. Access Modifiers Specifies accessibility (scope) of a data member, method, constructor or class. Types :  private  package-private (no explicit modifier)  protected  public There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc.
  112. 112. Access Modifier within class within package outside package by subclass only outside package private Y N N N package-private (no explicit modifier) Y Y N N protected Y Y Y N public Y Y Y Y Note: A class cannot be private or protected except nested class.
  113. 113. Mahika.a.motwani@gmail.com Modifier A B C D public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N N Visibiity The following table shows where the members of the A class are visible for each of the access modifiers that can be applied to them. Package 1 A B Package 2 C D subclass
  114. 114. Java Array Collection of similar type of elements. Contiguous memory location. Fixed size. Index based, first element of the array is stored at 0 index.
  115. 115. Types of Array: Single Dimensional Array Multidimensional Array Single Dimensional Array in java Syntax: dataType[] arr; (or) dataType []arr; (or) dataType arr[]; Instantiation : arrayRefVar=new datatype[size]; Declaration, Instantiation and Initialization : int a[]={33,3,4,5};//declaration, instantiation and initialization
  116. 116. Core Java
  117. 117. Mahika.a.motwani@gmail.com Diamond problem An ambiguity that can arise as a consequence of allowing multiple inheritance. Since Java 8 default methods have been permitted inside interfaces, which may cause ambiguity in some cases.
  118. 118. Mahika.a.motwani@gmail.com Diamond Structure:Case#1 [+] void m () <<default>> <<interface>> A <<interface>> B <<interface>> C [+] void main(String arg[]) <<static>> <<class>> D interface A { default void m() { System.out.println("m() from interface A "); } } interface B extends A { } interface C extends A { } public class D implements B,C { public static void main(String[] args) { new D().m(); } }
  119. 119. Mahika.a.motwani@gmail.com Diamond Structure:Case#2 [+] void m () <<default>> <<interface>> A [+] void m () <<default>> <<override>> <<interface>> B <<interface>> C [+] void main(String arg[]) <<static>> <<class>> D interface A { default void m() { System.out.println("m() from interface A "); } } interface B extends A { @Override default void m() { System.out.println("m() from interface B "); } } interface C extends A { } public class D implements B,C { public static void main(String[] args) { new D().m(); } }
  120. 120. Mahika.a.motwani@gmail.com Diamond Structure:Case#3 [+] void m () <<default>> <<interface>> A [+] void m () <<default>> <<override>> <<interface>> B [+] void m () <<default>> <<override>> <<interface>> C [+] void m () <<override>> [+] void main(String arg[]) <<static>> <<class>> D interface A { default void m() { System.out.println("m() from interface A "); } } interface B extends A { @Override default void m() { System.out.println("m() from interface B "); } } interface C extends A { @Override default void m() { System.out.println("m() from interface C"); } } public class D implements B,C { @Override public void m() { B.super.m(); } public static void main(String[] args) { new D().m(); } }

×