Session 3 - Classes, Methods _ Blocks and Objects _ Constructors
Session 3 - Classes, Methods _ Blocks and Objects _ Constructors
1. Can a Java source file have more than one class declaration?
Yes. However only one class can be declared as public and the java file name should be exactly same
as the public class name along with .java extension.
3. Can we have two classes with same name under the same package?
No.
4. Can we have class name same as the interface name under the same package?
No.
6. Could a Java class file exists even without filename and only extension(.java)?
Yes. The file is to be saved as .java without any file name. The source code can be compiled using javac
.java and run using java <className>
class JavaClass {
public static void main(String args[]) {
System.out.println(".java file content");
}
}
ClassNotFoundException Example.
package com.tutorials.classes;
}
8. What is Dynamic class loading?
A class can be loaded using one of the following methods:
• Class.forname,
• ClassLoader.findSystemClass,
• ClassLoader.loadClass.
loadClass is a ClassLoader method, so it uses an explicitly-provided loader, and initializes the class
lazily (on first use).
@Override
public boolean equals(Object o) {
if (this == o) // check 1
return true;
// null check
if (o == null)
return false;
// type check and cast
if (getClass() != o.getClass())
return false;
Employee emp = (Employee) o;
//numeric and identity fields first
if (!Objects.equals(this.emplId, emp.emplId)) return false;
// field comparison
return Objects.equals(firstName, emp.firstName)
&& Objects.equals(lastName, emp.lastName);
}
18. Can two objects which are not equal have the same hashCode?
Yes, possible. Two objects which are not equal to equals() method can still return same hashCode.
19. What happens when equals() is not consistent with compareTo() method?
java.util.Set implementations such as SortedSet, TreeSet uses compareTo method for comparing
objects. When compareTo does not return 0 while equals is true, it breaks Set contract and may result
in duplicates.
20. Difference between instanceof and getClass() method for checking type inside equals.
instanceof operator returns true, even if compared with subclass, for example, Subclass instanceof
Superclass is true, but with getClass() its false. By using getClass() you ensure that your equals()
implementation doesn't return true if compared with subclass object.
}
In case of calling a non-static (instance) method using null object reference, it will throw
NullPointerException.
fruit.nature();
}
}
Java interface default methods are also known as Defender Methods or Virtual extension methods.
A default method cannot override a method from java.lang.Object class as interfaces does not
extend Object.
Compilation error occurs when a class tries to implement two or more interfaces having a default
method with the same signature.
Other than multiple inheritance, there is no significant difference between an abstract class and an
interface in Java 8 by the addition of default method feature.
• Using default methods for interfaces eliminates the need for utility classes, for example, the
java.util.Collections utility class is not required when all of its methods are provided in the
Collection interface itself as default methods.
• It helps in extending interfaces without the concern of breaking the implementation classes.
• Default methods in interfaces enhances the Collections API in Java 8 to support lambda
expressions.
• Java interface default methods has bridged down the differences between interface
and abstract class.
• Interface implementing concrete classes can choose which default method to override and
can use interface default implementation itself.
The static interface method has method body and marked with static keyword in the method signature.
Fruits.eat();
}
}
Advantages of using static interface method in Java 8.
• Java interface static methods are suitable for providing utility function and acts as utility
methods, for example sorting a Collection, validations, reversing a collection etc.
• Java interface static method ensures quality and security by preventing the implementation
classes to override them.
39. Are Java static calls less expensive than non-static calls?
Static methods are usually faster (comparatively) as we don't need 'this' object reference for static calls.
However, the performance is negligible when compared to the non-static method calls and no decision
should be made based on performance when choosing static methods vs non-static methods.
No, we encounter compile time error. default modifier is used for methods with implementation.
static keyword identifies it is class based and it can be invoked without creating a class instance.
void is the return type of the method. Void indicates that the method does not return any value.
main is the name of the method which is invoked by JVM as a starting point of execution for an
application.
String args[] holds the command line parameters passed to the main method.
package com.javatutorials.urlshort;
public class Fruit {
Fruit() { // No parameters mentioned at open and close parenthesis. This is
// the default constructor.
System.out.println(" Example of a default constructor.");
}
What happens when the developer does not implement default constructor?
If there is no constructor in a class, compiler automatically creates a default constructor.
When there are parameterized constructors implemented, compile will not create the
default constructor.
In the below example, make String variable is initialized to null, numberofSeats to 0 and isItOldModel
to false.
boolean isItOldModel;
@Override
public String toString() {
return "Car make is " + make + " and it has " + numberofSeats
+ " seats and is it old model? " + isItOldModel + ".";
}
}
Output:
Car make is null and it has 0 seats and is it old model? false.
Copy-Constructor.
Java supports copy constructor like C++, however Java doesn't create a default copy constructor if
the developer does not provide its implementation.
String color;
String size;
Apple(Apple appleObj) {
this.color = appleObj.color;
this.size = appleObj.size;
}
@Override
public String toString() {
return "Apple of (" + color + " , " + size + ")";
}
System.out.println(greenApple);
System.out.println(redApple);
System.out.println(anotherGreenApple);
}
}
47. Difference between constructor and method in Java.
Java Constructor. Java Method.
Constructor initialize the state of an object. Method exhibits the behavior of an object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
In case of default constructor, the java compiler provides a Method is not provided by compiler in any
default constructor if you don't have any constructor. case.
Method name may or may not be same as
Constructor name must be same as the class name.
class name.
package org.javatutorials.accessModifer.protectedPackage;
class ClassWithPrivateConstructor {
private ClassWithPrivateConstructor() {
System.out.println("Hello from ClassWithPrivateConstructor");
}
public ExtendingClass() {
System.out.println("Hello from ExtendingClass");
}
new ExtendingClass();
}
}
Can the inner class with private constructor be extended?
Yes.
package org.javatutorials.accessModifer.protectedPackage;
class Parent {
private Parent() {
System.out.println("Hello from Parent");
}
}
55. Can you use this() and super() both together in a constructor?
No. Either this or super must be in first statement so we can have either one at a time and not both.
59. Can we call the constructor of a class more than once for an object in Java?
Constructor is called automatically when we create an object using new keyword. It is called only once
for an object at the time of object creation and hence, we cannot invoke the constructor again for an
object after it is created.
Using clone().
For example, take the below constructor for Employee class which take 2 arguments.
66. If a class has an explicit constructor, does compiler create default constructor?
No. compiler creates default constructor only if there is no explicit constructor.
68. What are the access modifiers that cannot be applied to a constructor?
final, static, abstract and synchronized keywords cannot be applied to a constructor.
}
}
70. Can you declare Constructor as final in Java?
No. It results in compile time error.