CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

Similar documents
this keyword in java javatpoint

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Answer1. Features of Java

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Inheritance and Polymorphism

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Class, Variable, Constructor, Object, Method Questions

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java

Chapter 5. Inheritance

Java Fundamentals (II)

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

C++ Important Questions with Answers

Inheritance. Transitivity

What is Inheritance?

Programming overview

INHERITANCE AND EXTENDING CLASSES

Arrays Classes & Methods, Inheritance

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Chapter 6 Introduction to Defining Classes

Instance Members and Static Members

20 Most Important Java Programming Interview Questions. Powered by

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Java static keyword static keyword

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Java Primer 1: Types, Classes and Operators

COMP 110/L Lecture 19. Kyle Dewey

1 Shyam sir JAVA Notes

CS260 Intro to Java & Android 03.Java Language Basics

Inheritance and Polymorphism

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Java: introduction to object-oriented features

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

INHERITANCE. Spring 2019

Inheritance (continued) Inheritance

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

CS-202 Introduction to Object Oriented Programming

Object Orientated Programming Details COMP360

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

ECE 122. Engineering Problem Solving with Java

Questions Answer Key Questions Answer Key Questions Answer Key

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

CS 251 Intermediate Programming Inheritance

Questions Answer Key Questions Answer Key Questions Answer Key

Tutorial 7. If it compiles, what does it print? Inheritance 1. Inheritance 2

Questions Answer Key Questions Answer Key Questions Answer Key

Accelerating Information Technology Innovation

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Declarations and Access Control SCJP tips

CS1150 Principles of Computer Science Objects and Classes

Constructor in Java. What is a Constructor? Rules for create a Java Constructor

What are the characteristics of Object Oriented programming language?

Java Object Oriented Design. CSC207 Fall 2014

COLLEGE OF ENGINEERING, NASHIK

Rules and syntax for inheritance. The boring stuff

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

COP 3330 Final Exam Review

Example: Count of Points

Lecture 02, Fall 2018 Friday September 7

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Lecture 2: Java & Javadoc

BBM 102 Introduction to Programming II Spring Inheritance

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Object Oriented Programming. I. Object Based Programming II. Object Oriented Programming

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

More Relationships Between Classes

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Chapter 4 Defining Classes I

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

Distributed Systems Recitation 1. Tamim Jabban

F I N A L E X A M I N A T I O N

Classes and Inheritance Extending Classes, Chapter 5.2

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

OVERRIDING. 7/11/2015 Budditha Hettige 82

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

CS111: PROGRAMMING LANGUAGE II

Midterm assessment - MAKEUP Fall 2010

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

Introduction to Programming Using Java (98-388)

Programming Language Concepts: Lecture 2

Static, Final & Memory Management

Character Stream : It provides a convenient means for handling input and output of characters.

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

ENCAPSULATION AND POLYMORPHISM

Inheritance Motivation

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Data Structures (list, dictionary, tuples, sets, strings)

JAVA OBJECT-ORIENTED PROGRAMMING

COMP 250 Fall inheritance Nov. 17, 2017

Transcription:

Constructor in Java 1. What are CONSTRUCTORs? Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. CONSTRUCTOR: The sole purpose of having CONSTRUCTORs is to create an instance of a class. They are invoked while creating an object of a class. CONSTRUCTORs can be public, private, or protected. If a CONSTRUCTOR with arguments has been defined in a class, you can no longer use a default no-argument CONSTRUCTOR you have to write one. They are called only once when the class is being instantiated. They must have the same name as the class itself. They do not return a value and you do not have to specify the keyword void. If you do not create a CONSTRUCTOR for the class, Java helps you by using a so called default no-argument CONSTRUCTOR. public class Boss{ Boss(String input) { //This is the CONSTRUCTOR name = "Our Boss is also known as : " + input; public static void main(string args[]) { Boss p1 = new Boss("Super-Man"); CONSTRUCTOR overloading: passing different number and type of variables as arguments all of which are private variables of the class. Example snippet could be as follows: public class Boss{ Boss(String input) { //This is the CONSTRUCTOR name = "Our Boss is also known as : " + input; Boss() { name = "Our Boss is a nice man. We don t call him names. ; public static void main(string args[]) { Boss p1 = new Boss("Super-Man"); Boss p2 = new Boss(); 2. What are Class CONSTRUCTORs S.N. 1 2 CONSTRUCTOR & Description String() This initializes a newly created String object so that it represents an empty character sequence. String(byte[] bytes) This constructs a new String by decoding the specified array of bytes using the platform's default

charset. 3 4 String(byte[] bytes, Charset charset) This constructs a new String by decoding the specified array of bytes using the specified charset. String(byte[] bytes, int offset, int length) This constructs a new String by decoding the specified subarray of bytes using the platform's default charset 3. Wha is a Copy CONSTRUCTOR unlike C++, Java doesn t create a default copy CONSTRUCTOR you have to write your own Following is an example Java program that shows a simple use of copy CONSTRUCTOR. // filename: Main.java class Complex { private double re, im; // A normal parametrized CONSTRUCTOR public Complex(double re, double im) { this.re = re; this.im = im; // copy CONSTRUCTOR Complex(Complex c) { System.out.println("Copy CONSTRUCTOR called"); re = c.re; im = c.im; // Overriding the tostring of Object class @Override public String tostring() { return "(" + re + " + " + im + "i)"; public class Main { public static void main(string[] args) { Complex c1 = new Complex(10, 15); // Following involves a copy CONSTRUCTOR call Complex c2 = new Complex(c1); // Note that following doesn't involve a copy CONSTRUCTOR call as // non-primitive variables are just references. Complex c3 = c2;//no new, therefore don t need copy CONSTRUCTOR System.out.println(c2); // tostring() of c2 is called here 4. What are the Rules for creating java constructor There are basically two rules defined for the constructor. 1. Constructor name must be same as its class name 2. Constructor must have no explicit return type

5. What are the Types of java constructors There are two types of constructors: 1. Default constructor (no-arg constructor) 2. Parameterized constructor 6. What is a Java Default Constructor A constructor that have no parameter is known as default constructor. 7. What is the Syntax of default constructor: <class_name>(){ 8. Give an Example of default constructor In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. class Bike1{ Bike1(){System.out.println("Bike is created"); Bike1 b=new Bike1(); Output: Bike is created Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

9. What is the purpose of default constructor? Default constructor provides the default values to the object like 0, null etc. depending on the type. Example of default constructor that displays the default values class Student3{ int id; void display(){system.out.println(id+" "+name); Student3 s1=new Student3(); Student3 s2=new Student3(); s1.display(); s2.display(); Output: 0 null 0 null Explanation:In the above class,you are not creating any constructor so compiler provides you a default constructor.here 0 and null values are provided by default constructor. 10. Java parameterized constructor A constructor that have parameters is known as parameterized constructor. 11. Why use parameterized constructor? Parameterized constructor is used to provide different values to the distinct objects. 12. Example of parameterized constructor In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. class Student4{ int id; Student4(int i,string n){ id = i; name = n; void display(){system.out.println(id+" "+name); Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display();

Output: 111 Karan 222 Aryan

13. What is Constructor Overloading in Java Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.the compiler differentiates these constructors by taking into account the number of parameters in the list and their type. Example of Constructor Overloading class Student5{ int id; int age; Student5(int i,string n){ id = i; name = n; Student5(int i,string n,int a){ id = i; name = n; age=a; void display(){system.out.println(id+" "+name+" "+age); Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25); s1.display(); s2.display(); Output: 111 Karan 0 222 Aryan 25 14. Differences Between Constructors and Methods The main difference is Constructor used to initialize the state of object must not have return type name same as the class name invoke implicitly compiler provide default constructor chained in particular order method expose the behaviour of object must have return type may or may not the same class name invoke explicitly compiler does't provide called unlimited number of times using the same object 15. What is a 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 In this example, we are going to copy the values of one object into another using java constructor. class Student6{ int id; Student6(int i,string n){ id = i; name = n; Student6(Student6 s){ id = s.id; name =s.name; void display(){system.out.println(id+" "+name); Student6 s1 = new Student6(111,"Karan"); Student6 s2 = new Student6(s1); s1.display(); s2.display(); Output: 111 Karan 111 Karan 16. Give an example of a Copy CONSTRUCTOR in Java // filename: Main.java class Complex { private double re, im; // A normal parametrized CONSTRUCTOR public Complex(double re, double im) { this.re = re; this.im = im; // copy CONSTRUCTOR Complex(Complex c) { System.out.println("Copy CONSTRUCTOR called"); re = c.re; im = c.im;

// Overriding the tostring of Object class @Override public String tostring() { return "(" + re + " + " + im + "i)"; public class Main { public static void main(string[] args) { Complex c1 = new Complex(10, 15); // Following involves a copy CONSTRUCTOR call Complex c2 = new Complex(c1); // Note that following doesn't involve a copy CONSTRUCTOR call as // non-primitive variables are just references. Complex c3 = c2; System.out.println(c2); // tostring() of c2 is called here 17. Give an example of copying without a constructor We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor. class Student7{ int id; Student7(int i,string n){ id = i; name = n; Student7(){ void display(){system.out.println(id+" "+name); Student7 s1 = new Student7(111,"Karan"); Student7 s2 = new Student7(); s2.id=s1.id; s2.name=s1.name; s1.display(); s2.display(); Output: 111 Karan 111 Karan 18. Q) Does constructor return any value? Ans:yes, that is current class instance (You cannot use return type yet it returns a value).

19. Can constructor perform other tasks instead of initialization? Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the constructor as you perform in the method. 20. How are this() and super() used with CONSTRUCTORs? this() is used to invoke a CONSTRUCTOR of the same class. super() is used to invoke a superclass CONSTRUCTOR. 21. Calling a CONSTRUCTOR From a CONSTRUCTOR In Java it is possible to call a CONSTRUCTOR from inside another CONSTRUCTOR. When you call a CONSTRUCTOR from inside another CONSTRUCTOR, you use the this keyword to refer to the CONSTRUCTOR. Here is an example of calling one CONSTRUCTOR from within another CONSTRUCTOR in Jav public class Employee { private String firstname = null; private String lastname = null; private int birthyear = 0; public Employee(String first, String last, int year ) { firstname = first; lastname = last; birthyear = year; public Employee(String first, String last){ this(first, last, -1); Notice the second CONSTRUCTOR definition. Inside the body of the CONSTRUCTOR you find this Java statement: this(first, last, -1); The this keyword followed by parentheses and parameters means that another CONSTRUCTOR in the same Java class is being called. Which other CONSTRUCTOR that is being called depends on what parameters you pass to the CONSTRUCTOR call (inside the parentheses after the this keyword). In this example it is the first CONSTRUCTOR in the class that is being called. 22. Calling CONSTRUCTORs in Superclasses In Java a class can extend another class. When a class extends another class it is also said to "inherit" from the class it extends. The class that extends is called the subclass, and the class being extended is called the superclass. A class that extends another class does not inherit its CONSTRUCTORs. However, the subclass must call a CONSTRUCTOR in the superclass inside one of the subclass CONSTRUCTORs! Look at the following two Java classes. The class Car extends (inherits from) the class Vehicle. public class Vehicle { private String regno = null; public Vehicle(String no) {

this.regno = no; public class Car extends Vehicle { private String brand = null; public Car(String br, String no) { super(no); this.brand = br; Notice the CONSTRUCTOR in the Car class. It calls the CONSTRUCTOR in the superclass using this Java statement: super(no); Using the keyword super refers to the superclass of the class using the super keyword. When super keyword is followed by parentheses like it is here, it refers to a CONSTRUCTOR in the superclass. In this case it refers to the CONSTRUCTOR in the Vehicle class. Because Car extends Vehicle, the Car CONSTRUCTORs must all call a CONSTRUCTOR in the Vehicle. 23. Java CONSTRUCTOR Access Modifiers For instance, if a CONSTRUCTOR is declared protected then only classes in the same package, or subclasses of that class can call that CONSTRUCTOR. A class can have multiple CONSTRUCTORs, and each CONSTRUCTOR can have its own access modifier. Thus, some CONSTRUCTORs may be available to all classes in your application, while other CONSTRUCTORs are only available to classes in the same package, subclasses, or even only to the class itself (private CONSTRUCTORs). 24. Can a CONSTRUCTOR be made final? No, this is not possible. 25. What's the difference between CONSTRUCTORs and other methods? CONSTRUCTORs must have the same name as the class and cannot return a value. They are only called once while regular methods could be called many times. 26. Can you call one CONSTRUCTOR from another if a class has multiple CONSTRUCTORs? Yes, use this() syntax. 27. Can CONSTRUCTOR be inherited? No, CONSTRUCTOR cannot be inherited. 28. Where and how can you use a private CONSTRUCTOR? Private CONSTRUCTOR is used if you do not want other classes to instantiate the object and to prevent subclassing. 29. What s the point of having a private CONSTRUCTOR? This may be news to you: in Java, it is possible to have a private CONSTRUCTOR. Why one would want to use one is explored below. The private modifier when applied to a CONSTRUCTOR works in much the same way as when applied to a normal method or even an instance variable. Defining a CONSTRUCTOR with the private modifier says that only the native class (as in the class in which the private CONSTRUCTOR is defined) is allowed to create an instance of the class, and no other caller is

permitted to do so. There are two possible reasons why one would want to use a private CONSTRUCTOR 3. first is that you don t want any objects of your class to be created at all, and the 4. second is that you only want objects to be created internally as in only created in your class. 30. Private CONSTRUCTORs can prevent creation of objects The other possible reason for using a private CONSTRUCTOR is to prevent object construction entirely. When would it make sense to do something like that? Of course, when creating an object doesn t make sense and this occurs when the class only contains static members. And when a class contains only static members, those members can be accessed using only the class name no instance of the class needs to be created. Java always provides a default, no-argument, public CONSTRUCTOR if no programmerdefined CONSTRUCTOR exists. Creating a private no-argument CONSTRUCTOR essentially prevents the usage of that default CONSTRUCTOR, thereby preventing a caller from creating an instance of the class. Note that the private CONSTRUCTOR may even be empty 31. Can an INTERFACE extend another INTERFACE? Yes an INTERFACE can inherit another INTERFACE, for that matter an INTERFACE can extend more than one INTERFACE. 32. If a method is declared as protected, where may the method is accessed? A protected method may only be accessed by classes or INTERFACES of the same package or by subclasses of the class in which it is declared. 33. What is CONSTRUCTOR chaining and how is it achieved in Java? A child object CONSTRUCTOR always first needs to construct its parent. In Java it is done via an implicit call to the no-args CONSTRUCTOR as the first statement.