Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Session 3 - Classes, Methods _ Blocks and Objects _ Constructors

Uploaded by

Ayush Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Session 3 - Classes, Methods _ Blocks and Objects _ Constructors

Uploaded by

Ayush Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

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.

2. What is the data type of System.out?


out is of type PrintStream and it is a static member in the System class.

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.

5. What is the base class of all classes?


java.lang.Object class.

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>

For e.g., .java file content:

class JavaClass {
public static void main(String args[]) {
System.out.println(".java file content");
}
}

7. Difference Between ClassNotFoundException & NoClassDefFoundError.


Both of these errors are related to missing classes in the classpath, however the main difference lies
how it originate. ClassNotFoundException occurs when you try to load a class at runtime by using
Class.forName() or loadClass() and requested class is not present in classpath. It is thrown when an
application tries to load in a class through its name, but no definition for the class with the specified
name could be found. NoClassDefFoundError is encountered when the class was available at compile
time but not during runtime.

ClassNotFoundException Example.
package com.tutorials.classes;

public class ExampleClassNotFoundException {

private static final String CLASS_TO_LOAD = "com.tutorials.classes.NotCreatedClass";

public static void main(String[] args) {


try {
Class loadedClass = Class.forName(CLASS_TO_LOAD);
System.out.println("Class " + loadedClass + " found successfully!");
} catch (ClassNotFoundException ex) {
System.err.println("ClassNotFoundException was caught: "
+ ex.getMessage());
ex.printStackTrace();
}
}

}
8. What is Dynamic class loading?
A class can be loaded using one of the following methods:

• Class.forname,
• ClassLoader.findSystemClass,
• ClassLoader.loadClass.

Difference: Class.forName() vs ClassLoader.loadClass().


Class.forName() uses the caller's classloader and initializes the class (runs static intitializers, etc.).

loadClass is a ClassLoader method, so it uses an explicitly-provided loader, and initializes the class
lazily (on first use).

9. Which class implements clone method- Cloneable or Object in Java?


java.lang.Object implements the clone() method. Clonable is a marker interface and it does not have
any methods. Object.clone() is a native method implemented using C, C++ or any other native language.

10. When are class static variables loaded in memory in Java?


At runtime immediately after the class has been loaded.

11. When a class is initialized in Java?


After class loading, initialization of class takes place by initializing all static members of class. A Java
class's static initialization usually happens immediately before the first time one of the following events
occurs:

• an instance of the class is created,


• a static method of the class is invoked,
• a static field of the class is assigned,
• a non-constant static field is used, or
• for a top-level class, an assert statement lexically nested within the class is executed.

12. What are the rules of class initialization in Java?


Classes are initialized from top to bottom fashion so that fields declared on top initialized before
field declared in bottom. Super Class is initialized before Sub Class or derived class is initialized in
Java. If Class initialization is triggered due to the access of a static field, only Class which
has declared static field is initialized and it doesn't trigger initialization of super class or sub
class even if static field is referenced by type of Sub Class, Sub Interface or by implementation class of
interface. Interface initialization in Java doesn't cause super interfaces to be initialized. static fields are
initialized during static initialization of class while non static fields are initialized when instance of class
is created. It means static fields are initialized before non-static fields in Java. non static fields are
initialized by constructors in Java. sub class constructor implicitly calls super class constructor before
doing any initialization, which guarantees that non static or instance variables of super class is
initialized before sub class.

13. Different type of cloning in Java.


Java supports 2 type of cloning: - Deep and shallow cloning. By default shallow clone is used in Java.
Object class has a method clone() which does shallow cloning.

14. Explain Shallow copy in Java.


Shallow clone is a copying the reference pointer to the object, which mean the new object is pointing
to the same memory reference of the old object. The memory usage is less in case of shallow copy.

15. Explain deep copy in Java.


Deep copy of an object will have exact copy of all the fields of original object just like shallow copy.
But in additional, if original object has any references to other objects as fields, then copy of those
objects are also created by calling clone() method on them. That means clone object and original object
will be 100% disjoint. They will be 100% independent of each other. Any changes made to clone object
will not be reflected in original object or vice-versa. To create a deep copy of an object, you have to
override the clone() method.

16. Difference between shallow and deep copy in Java.


Shallow copy. Deep copy.
Cloned Object and the original object are not 100% Cloned Object and original object are 100%
disjoint. disjoint.
Any changes to the cloned object will be reflected Changes made to cloned object won't be reflected
in original object or vice versa. to original object or vice versa.
Default version of clone method creates the To create the deep copy of an object, you have to
shallow copy of an object. override clone method.
Shallow copy is preferred if an object has only Deep copy is preferred if an object has references
primitive fields. to other objects as fields.
Shallow copy is fast and cost effective. Deep copy is slow and very expensive.

17. How to implement equals method correctly?


Consider that you are overriding equals method for Employee Class having empId, firstName and
lastName.

1. Check for reference equality, if equal then return true.


2. Check for null check on the object argument being passed, if null return false.
3. Compare getClass methods, if different return false.
4. Always compare numeric and identify fields first.
5. Check for field's references first and then check for null and equality.
6. Override hashcode method whenever you override equals method.

The above steps are illustrated in the below example.

@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.

21. Can a main method be declared final?


Yes, so that the subclass cannot override main() method.

22. Difference between arguments and parameters in Java.


A parameter is that appears in the definition of the method. An argument is the instance or value passed
to the method during runtime when the method is invoked.

23. Is the main() method required for all java classes?


No. main() method is defined only if the java class is an application and has to execute.

24. What is the return type of main() method?


void. main() method does not return any value.

25. Why does the main() method declared static?


JVM need to access the main() method even before the class instantiation so begin the execution. so it
is declared static.

26. What is the argument for main() method?


There is only one argument that main() method accepts. main() method accepts an array of string object
as an argument.

27. Can a main() method be overloaded?


Yes.
28. When no command line arguments are passed, does the String array parameter of main()
method be null?
It is an empty Array with zero elements and not null.

public class MainMethodClass {

public static void main(String[] args) {

System.out.println("Size of the Arg Array=" + args.length);


}
}
Output: 0

29. Can we invoke a static method on a null object reference in Java?


Yes. The compiler optimizes the code to invoke the static method using null object reference since
object instance is not required to invoke a static method.

public class StaticMethodUsingNull {

static void printWelcomeMessage() {


System.out.println("Welcome to javapedia.net!");
}

public static void main(String[] args) {


StaticMethodUsingNull myRef = null;
myRef.printWelcomeMessage(); /*Message will be printed sucessfully*/

}
In case of calling a non-static (instance) method using null object reference, it will throw
NullPointerException.

30. Explain the Default method for interfaces in Java 8.


In Java 8, a new feature "default method implementation for interfaces" is introduced
that facilitates backward compatibility for the old interfaces to leverage the lambda expression
capability of Java 8 and also existing libraries implementing these interfaces need not have to provide
its implementation for the new functionality/method added to the interface. For example,
java.util.List or Collection interface does not have forEach method declaration. Thus, calling such
methods will break the collection framework implementations. Java 8 introduces default method so that
List/Collection interface can have a default implementation of forEach method, and the class
implementing these interfaces need not have to implement the same. Thus, default methods enable you
to add new functionality to the interfaces of your libraries and ensure backward compatibility with the
codes written using the older versions of those interfaces without having to implement the new
functionality. For creating a default method in Java interface, we need to use default keyword with the
method signature.

public interface Fruits {


default void nature(){
System.out.println("I am Sweet.");
}
}
The default methods are non-static and can be accessed from the Implementing class object as shown
in the below example.

public class OrangeClass implements Fruits {

public static void main(String[] args) {


Fruits fruit = new OrangeClass();

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.

Advantages of default method in Interface feature in Java 8.

• 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.

31. Explain the static interface methods feature in Java 8.


The interface static methods are concrete methods implemented in the interface that prevents the
implementation classes from overriding to ensure the proper and uniform implementation being
used across all the implementation classes.

The static interface method has method body and marked with static keyword in the method signature.

public interface Fruits {


static void eat() {
System.out.println("Enjoy!");
}
}
Java interface static methods are visible to interface methods only and it can be invoked by interface
name itself.

public class OrangeClass implements Fruits {

public static void main(String[] args) {

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.

32. Difference between default and static methods in Java interface.


Default method. Static method.
default method are used as a default
implementation for classes that implements that static method in interface is used as Helper methods.
interface.
default methods can be invoked by the static methods are similar to static class methods and
implementation class objects. can be invoked using Interface name.

33. Explain pass by reference and pass by value in Java?


When an object is passed by value, this means that a copy of the object is passed. Thus, even if changes
are made to that object, it doesn't affect the original value. When an object is passed by reference, this
means that the actual object is not passed, rather a reference of the object is passed. Thus, any changes
made by the external method, are also reflected in all places.

34. Difference between System.exit(0), exit (1) and exit(-1) in Java.


Zero represents that the program ended successfully. Any number greater than zero represents program
execution failed. Number less than zero represents program execution error.

35. What is virtual function/method in Java?


In Java, all non-static methods are considered as virtual functions. The Final methods cannot be
overridden and the private methods cannot be inherited so it is considered as non-virtual.

36. Can we define a static method in a Java interface?


With Java 8, interfaces can have static methods. They can also have concrete instance methods, but
not instance fields.

37. Explain method chaining in Java.


Method chaining is a mean by which fluent API could be used so that multiple setters on a method be
invoked continuously by just using dot(.) that improves readability and less code. To achieve method
chaining update the setters to return the object instance or by using this keyword.

38. What is a method reference in Java 8?


A method reference is a Java 8 construct that can be used for referencing a method without invoking it.
It is used for treating methods as Lambda Expressions. They can only be used to replace a single-method
lambda expression.

The general syntax of a method reference: Object :: methodName


In method reference, you place the object (or class) that contains the method before the :: operator and
the name of the method after it without arguments.

Types of method references in Java 8.

• A method reference to a static method.


• A method reference to an instance method of an object of a particular type.
• A method reference to an instance method of an existing object.
• A method reference to a constructor.

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.

40. What is lambda expression in Java 8?


A lambda expression is an anonymous function that you can use to create delegates or expression tree
types. By using lambda expressions, you can write local functions that can be passed as arguments or
returned as the value of function calls. A lambda expression is the most convenient way to create that
delegate.

41. Is abstract modifier allowed in default method?

No, we encounter compile time error. default modifier is used for methods with implementation.

42. What is the scope of default methods in Java8?


All the method declarations in an interface, including default methods, are implicitly public, so you can
omit the public modifier.

43. Why Java doesn't allow overriding of static methods?


Overriding depends on having an instance of an class and static method is not associated to instance of
the class.

44. Explain public static void main(String args[]) method signature.


public access modifier specifies who can access this method. Public will be accessible by any Class
from any package.

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.

45. How to call a default method of an interface in a class?


Use super keyword along with interface name to invoke a default method.

public interface Animal {


default void feed() {
System.out.println("Feed some food to animals");
}
}

public class Dog implements Animal{


public void feed() {
Animal.super.feed();
}
}
46. How to invoke a static method of an interface?
Invoke the static method using the name of the interface.

public interface Animal {


static void doSwim() {
System.out.println("Animal can swim");
}
}
public class Dog implements Animal {
public void canSwim() {
Animal.doSwim();
}
}

46. What is a Constructor?


A constructor is a construct similar to java method without any return type. A constructor gets invoked
when a new object is created. Every class has a constructor. In case the developer does not provide
a constructor for a class, the Java compiler (Javac) creates a default constructor for that class.

Rules for creating a Java constructor.

• Constructor name must match its class name.


• Constructor must not have any return type.
Two types of constructors:
1. Default constructor (no-arg constructor).
2. Parametrized constructor.

Java Default Constructor.


The constructor that takes no parameters is termed as default constructor.

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.");
}

public static void main(String[] str) {


Fruit fruit = new Fruit();
}
}
Java parameterized constructor.
A constructor that takes arguments is referred as parameterized constructor.

Advantages of parameterized constructor.


Customize initializing the property state of the object using user defined values thus eliminates using
default values.

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.

Purpose of default constructor.


Default constructor initializes the instance variables to its default values if not initalized explicitly
depending on the type.

For objects, default constructor initializes it to null, int with 0.

In the below example, make String variable is initialized to null, numberofSeats to 0 and isItOldModel
to false.

public class Car {


String make;
int numberofSeats;

boolean isItOldModel;

@Override
public String toString() {

return "Car make is " + make + " and it has " + numberofSeats
+ " seats and is it old model? " + isItOldModel + ".";
}

public static void main(String[] args) {

Car newCar = new Car();


System.out.println(newCar);

}
Output:

Car make is null and it has 0 seats and is it old model? false.

Constructor Overloading in Java.


The constructor overloading is similar to method overloading in Java. Different constructors can be
created for a single class. Each constructor must have its own unique parameter list.

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.

public class Apple {

String color;
String size;

Apple(String color, String size) {


this.color = color;
this.size = size;
}

Apple(Apple appleObj) {
this.color = appleObj.color;
this.size = appleObj.size;
}

@Override
public String toString() {
return "Apple of (" + color + " , " + size + ")";
}

public static void main(String[] str) {


Apple greenApple = new Apple("Green", "small");

Apple redApple = new Apple("Red", "large");

Apple anotherGreenApple = new Apple(greenApple);

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.

48. What are pass by reference and pass by value?


When an object is passed by value, an exact copy of the object is passed. Thus, if changes are made to
that object, it doesn't affect the original object. When an object is passed by reference, the actual object
is not passed, instead a reference of the object is passed. Any changes made by the external method,
affects the original object.

49. Can constructor perform other tasks instead of initialization?


Yes. In addition to initializing the state of an object, construct may initialize threads, invoke methods
etc. Constructor exhibits behaviour as same as any Java method in terms of activities that it can
perform.

50. Can a constructor call/invoke a static method?


Yes.

51. Can a constructor invoke a non-static/instance method?


Yes.

52. Can abstract class have constructors?


Yes, abstract class can define constructor altough abstract class cannot be initiated.

53. What is the access modifier of the Default constructor?


It depends on the Class's access modifier. If the Class declared as public, then the default constructor
access modifier will be public. If the class is protected, then default constructor is protected. The same
rule applies for default access and private.

54. Can the class with private constructor be extended?


No, in case of outer classes. The below program will generate compile time error.

package org.javatutorials.accessModifer.protectedPackage;
class ClassWithPrivateConstructor {
private ClassWithPrivateConstructor() {
System.out.println("Hello from ClassWithPrivateConstructor");
}

public class ExtendingClass extends ClassWithPrivateConstructor {

public ExtendingClass() {
System.out.println("Hello from ExtendingClass");
}

public static void main(String args[]) {

new ExtendingClass();
}
}
Can the inner class with private constructor be extended?
Yes.

package org.javatutorials.accessModifer.protectedPackage;

public class PrivateConstructorInnerClass {

class Parent {
private Parent() {
System.out.println("Hello from Parent");
}
}

class Child extends Parent {


public Child() {
System.out.println("Hello from Child");
}
}
public static void main(String[] str) {
PrivateConstructorInnerClass pc = new PrivateConstructorInnerClass();
pc.new Child();
}
}
Output:

Hello from Parent


Hello from Child

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.

56. Can constructor be synchronized in Java?


No. constructor cannot be synchronized.

57. Is constructor inherited?


No, constructor is not inherited.

58. Can a constructor be final?


No, constructor cannot be final.

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.

60. Is constructor called when cloning in Java?


No. It doesn't invoke constructor.

61. Different ways to create an object in Java.


There are 5 different ways to create an object in Java.

Using new keyword.

MyObject object = new MyObject();


Using Class.forName().

Quiz object = (Quiz) Class.forName("net.javapedia.quiz.model.Quiz").newInstance();

Using clone().

Quiz object1 = new Quiz();


Quiz object2 = (Quiz ) object1.clone();

Using object deserialization.


ObjectInputStream inStream = new ObjectInputStream(myInputStream );
Quizobject = (Quiz) inStream.readObject();

Using Reflection newInstance() method of Constructor.

Constructor<Quiz> constructor = Quiz.class.getConstructor();


Quiz quiz = constructor.newInstance();
62. Difference between Class.newInstance() and Constructor.newInstance().
The Class.newInstance() method can only invoke a no-arg constructor.

Quiz object = (Quiz) Class.forName("net.javapedia.quiz.model.Quiz").newInstance();


To create objects using reflection with parameterized constructor you need to use
Constructor.newInstance().

final Employee emp = Employee.class.getConstructor(


int.class, int.class, double.class).newInstance(_xval1,_xval2,_pval)
How to Initialize class with Class.forName() that has parameterized constructor?
Use Class.getConstructor() and call Constructor.newInstance() method.

For example, take the below constructor for Employee class which take 2 arguments.

public Employee(int empId, String name) {


}
We need to invoke getConstructor method by passing argument values as shown below.

Constructor empC = Class.forName("Employee").getConstructor(Integer.TYPE, String.class);


Employee employee= (Employee) empC.newInstance(345, "John Smith");
63. Can you define a method with the same name as the class?
Yes, it is allowed. However not recommended due to coding standards.

64. What happens when we add a return type to the constructor?


JVM considers it as a method instead. Only the return type differentiates between constructor and the
method.

65. Is Constructor definition mandatory?


Not at all However compiler will define one (default constructor) if not defined explicitly.

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.

67. Can we throw exceptions from a constructor?


Yes, constructor can have throws clause.

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.

69. What is constructor chaining?


Constructor Chaining is a technique of calling another constructor from one constructor. this() is used
to call same class constructor while super() is used to call super class constructor.

70. How do I call subclass constructor from superclass constructor?


No. This is not possible.

71. What is No-arg constructor or default constructor.?


Constructor without arguments is called the no-arg constructor. Default constructor in Java is always a
no-arg constructor and it is created by the compiler when no explicit constructor exists.

public class MyClass


{
public MyClass() //No-arg constructor
{

}
}
70. Can you declare Constructor as final in Java?
No. It results in compile time error.

You might also like