Java面试题每日10问(3)

news2024/11/18 23:30:23

Core Java - OOPs Concepts: static keyword Interview Questions

1.What if the static modifier is removed from the signature of the main method?

Program compiles. However, at runtime, It throws an error “NoSuchMethodError.”

2. What is the difference between static (class) method and instance method?

static or class methodinstance method
1)A method that is declared as static is known as the static method.A method that is not declared as static is known as the instance method.
2)We don’t need to create the objects to call the static methods.The object is required to call the instance methods.
3)Non-static (instance) members cannot be accessed in the static context (static method, static block, and static nested class) directly.Static and non-static variables both can be accessed in instance methods.
4)For example: public static int cube(int n){ return nnn;}For example: public void msg(){…}.

3.Can we make constructors static?

  • the static context (method, block, or variable) belongs to the class, not the object.
  • Since Constructors are invoked only when the object is created, there is no sense to make the constructors static.
  • if you try to do so, the compiler will show the compiler error.

4.Can we make the abstract methods static in Java?

  • In Java, if we make the abstract methods static, It will become the part of the class, and we can directly call it which is unnecessary.
  • Calling an undefined method is completely useless therefore it is not allowed.

5.Can we declare the static variables and methods in an abstract class?

  • Yes, we can declare static variables and methods in an abstract method.
  • there is no requirement to make the object to access the static context
  • we can access the static context declared inside the abstract class by using the name of the abstract class.
abstract class Test  
{  
    static int i = 102;  
    static void TestMethod()  
    {  
        System.out.println("hi !! I am good !!");  
    }  
}  
public class TestClass extends Test   
{  
    public static void main (String args[])  
    {  
        Test.TestMethod();  
        System.out.println("i = "+Test.i);  
    }  
}  
hi !! I am good !!
i = 102

Core Java - OOPs Concepts: Inheritance Interview Questions

6.What is this keyword in java?

  • this is a reference variable that refers to the current object.
  • it can be used to refer to current class properties such as instance methods, variable, constructors, etc.
  • It can also be passed as an argument into the methods or constructors.
  • It can also be returned from the method as the current class instance.
    在这里插入图片描述

7.What are the main uses of this keyword?

There are the following uses of this keyword.

  1. this can be used to refer to the current class instance variable.
  2. this can be used to invoke current class method (implicitly)
  3. this() can be used to invoke the current class constructor.
  4. this can be passed as an argument in the method call.
  5. this can be passed as an argument in the constructor call.
  6. this can be used to return the current class instance from the method.

1.this can be used to refer to the current class instance variable.

The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.

without this keyword

class Student{  
	int rollno;  
	String name;  
	float fee;  
	Student(int rollno,String name,float fee){  
		rollno=rollno;  
		name=name;  
		fee=fee;  
	}  
	void display(){
		System.out.println(rollno+" "+name+" "+fee);}  
	}  
	class TestThis1{  
		public static void main(String args[]){  
		Student s1=new Student(111,"ankit",5000f);  
		Student s2=new Student(112,"sumit",6000f);  
		s1.display();  
		s2.display();  
	}
}  
0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.

class Student{  
	int rollno;  
	String name;  
	float fee;  
	Student(int rollno,String name,float fee){  
		this.rollno=rollno;  
		this.name=name;  
		this.fee=fee;  
	}  
	void display(){System.out.println(rollno+" "+name+" "+fee);}  
}  
  
class TestThis2{  
	public static void main(String args[]){  
		Student s1=new Student(111,"ankit",5000f);  
		Student s2=new Student(112,"sumit",6000f);  
		s1.display();  
		s2.display();  
	}
}  
111 ankit 5000.0
112 sumit 6000.0

If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:

class Student{  
	int rollno;  
	String name;  
	float fee;  
	Student(int r,String n,float f){  
		rollno=r;  
		name=n;  
		fee=f;  
	}  
	void display(){System.out.println(rollno+" "+name+" "+fee);
	}  
}  
  
class TestThis3{  
public static void main(String args[]){  
	Student s1=new Student(111,"ankit",5000f);  
	Student s2=new Student(112,"sumit",6000f);  
	s1.display();  
	s2.display();  
	}
}  
111 ankit 5000.0
112 sumit 6000.0

2.this can be used to invoke current class method (implicitly)

The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.
在这里插入图片描述

public class Test2 {
    public static void main(String args[]) {
        Test2 a = new Test2();
        a.n();
    }
    void m(){System.out.println("hello a");}
    void n(){
        System.out.println("hello b");
        //m(); or use this.but compiler automatically adds this keyword
        this.m();
    }
}
hello b
hello a

3. this() can be used to invoke the current class constructor.

The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:

public class Test2 {
    Test2(){
        System.out.println("hello a");
    }
    Test2(int x){
        this();
        System.out.println(x);
    }

    public static void main(String args[]){
        Test2 a= new Test2(5);
    }
}

hello a
5

Calling parameterized constructor from default constructor:

public class Test2 {
    Test2(){
        this(5);
        System.out.println("hello a");
    }
    Test2(int x){
        System.out.println(x);
    }

    public static void main(String args[]){
        Test2 a= new Test2();
    }
}

5
hello a

Real usage of this() constructor call

  • The this() constructor call should be used to reuse the constructor from the constructor.
  • It maintains the chain between the constructors i.e. it is used for constructor chaining.
public class Student {
    int rollno;
    String name,course;
    float fee;
    Student(int rollno,String name,String course){
        this.rollno=rollno;
        this.name=name;
        this.course=course;
    }
    Student(int rollno,String name,String course,float fee){
        this(rollno,name,course);//reusing constructor
        this.fee=fee;
    }
    void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
    
    public static void main(String args[]){
        Student s1=new Student(111,"ankit","java");
        Student s2=new Student(112,"sumit","java",6000f);
        s1.display();
        s2.display();
    }
}

111 ankit java 0.0
112 sumit java 6000.0

📢 Call to this() must be the first statement in constructor.
在这里插入图片描述

4. this can be passed as an argument in the method call.

The this keyword can also be passed as an argument in the method. It is mainly used in the event handling.
Application of this that can be passed as an argument:
In event handling (or) in a situation where we have to provide reference of a class to another one. It is used to reuse one object in many methods.

public class Student {
    void method1(Student student){
        System.out.println("method is invoked");
    }
    void method2(){
        method1(this);
    }
    
    public static void main(String args[]){
        Student s1 = new Student();
        s1.method2();

    }
}

method is invoked

5. this can be passed as an argument in the constructor call.

We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes.


// Java code for using this as an argument in constructor
// call
// Class with object of Class B as its data member
class A
{
    B obj;
     
    // Parameterized constructor with object of B
    // as a parameter
    A(B obj)
    {
        this.obj = obj;
        
     // calling display method of class B
        obj.display();
    }
     
}
 
class B
{
    int x = 5;
     
    // Default Constructor that create a object of A
    // with passing this as an argument in the
   // constructor
    B()
    {
        A obj = new A(this);
    }
     
    // method to show value of x
    void display()
    {
        System.out.println("Value of x in Class B : " + x);
    }
     
    public static void main(String[] args) {
        B obj = new B();
    }
}
Value of x in Class B : 5

6. this can be used to return the current class instance from the method.

We can return this keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive)

public class Student {
    Student getStudent(){
        return this;
    }
    void method(){
        System.out.println("hello");
    }

    public static void main(String[] args) {
        new Student().getStudent().method();
    }
}

hello

Proving this keyword
we prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this, output of both variables are same.

public class Student {
    void method(){
        System.out.println(this);
    }

    public static void main(String[] args) {
        Student student = new Student();
        System.out.println(student);
        student.method();
    }
}

gengic.Student@1b6d3586
gengic.Student@1b6d3586

8.Can this keyword be used to refer static members?

  • Yes, this keyword is used to refer static members because this is just a reference variable refers to the current class object.
  • it is unnecessary to access static variables through objects, therefore, it is not the best practice to use this to refer static members.
public class Test   
{  
    static int i = 10;   
    public Test ()  
    {  
        System.out.println(this.i);      
    }  
    public static void main (String args[])  
    {  
        Test t = new Test();  
    }  
}  
10

9. What are the advantages of passing this into a method instead of the current class object itself?

  • this refers to the current class object, it must be similar to the current class object.
  • -there can be two main advantages of passing this into a method instead of the current class object.
    – this is a final variable. Therefore, this cannot be assigned to any new value whereas the current class object might not be final and can be changed.
    – this can be used in the synchronized block.

10.What is the Inheritance?

  • Inheritance is a mechanism by which one object acquires all the properties and behavior of another object of another class.
  • It is used for Code Reusability and Method Overriding. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes.
  • When you inherit from an existing class, you can reuse methods and fields of the parent class.
  • Moreover, you can add new methods and fields in your current class also.
  • Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

There are five types of inheritance in Java.

Single-level inheritance
Multi-level inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/148077.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

2023年会发生什么,一点都不会神秘

文/明道云创始人任向晖我很少写市场预测文章,是因为影响经济活动的要素实在太多了。做任何预测的时候,想明白了一二,但没有预计到三,结果可能就完全不一样。过去三年的疫情就是一个典型的例子。但是这个冬天的预测显得格外重要一些…

Redis+注解实现API接口防刷限流

前言 在开发分布式高并发系统时有三把利器来保护系统:缓存、降级、限流。 缓存: 缓存的目的是提升系统访问速度和增大系统处理容量;降级:降级是当服务出现问题或者影响到核心流程时,需要暂时屏蔽掉,待高峰或者问题解…

软件测试之维护性测试

维护性测试用于评估系统能够被预期的维护人员修改的有效性和效率的程度,可从模块化、可重用性、易分析性、易修改性、易测试性、易维护性 1)模块化:评估由独立组件组成的系统或计算机程序,其中一个组件的变更对其他组件的影响大小程度&#x…

【Android 车载 App】实现座椅调节控制十字指针的效果

【Android 车载 App】实现座椅调节控制十字指针的效果效果展示实现方法思路代码第一步,画两条十字虚线第二步,在每个虚线的末端画出圆角三角形第三步,在十字虚线的中间位置画出两个同心圆,一个填充内容,一个描边第四步…

一款新兴的操作pcap的神器

一 前言有机会接触到这款软件,还是同事的一个图,图介绍了开源项目Zed和基于Zed做的一款全流量安全产品Brim。整个产品其实是不少开源项目的一个小集成,只所以感兴趣,除了brim在github有1.5k个star的原因外,更吸引我的是…

缓存的数据一致性

文章目录1.先更新缓存,再更新DB2.先更新DB,再更新缓存3.先删除缓存,后更新DB4.先更新DB,后删除缓存 (推荐)前言: 只要使用到缓存,无论是本地内存做缓存还是使用 redis 做缓存&#…

Neo4j网页服务器端口Cypher操作直接创建知识图谱

案例1:创建新节点、关系 CREATE (n:美国企业家{name:马斯克}) MERGE (n) <-[:主公]- (n1:总统{name:拜登}) RETURN *创建其他节点的时候,可以一次输入:例如 CREATE

代码随想录day32

第32天 前言 终于到周六了&#xff0c;明天可以休息了&#xff0c;哈哈哈 122. 买卖股票的最佳时机 II 题目 给定一个数组&#xff0c;它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易&#xff08;多…

DenseNet详解

入门小菜鸟&#xff0c;希望像做笔记记录自己学的东西&#xff0c;也希望能帮助到同样入门的人&#xff0c;更希望大佬们帮忙纠错啦~侵权立删。 ✨完整代码在我的github上&#xff0c;有需要的朋友可以康康✨ https://github.com/tt-s-t/Deep-Learning.git 目录 一、DenseNet网…

深度学习——语言模型(笔记)

语言模型&#xff1a;NLP经典的模型 1.语言模型 ①长度为T的文本序列中词元依次是x1,…,xT&#xff0c;xT被认为是文本序列在时间t处的观测或标签。在给定文本序列&#xff0c;语言模型的目标是估计序列的联合概率p(x1,…,xT) ②序列模型的核心是整个序列文本所出现的概率 应…

国家基础地理信息中心行政边界等矢量数据免费下载保姆级教程--关于地理数据收集与处理的基本工具推荐(7)

关于地理数据收集与处理的基本工具推荐系列&#xff0c;有导航&#xff0c;不迷路&#xff1a; 关于地理数据收集与处理的基本工具推荐(1) —高分辨率卫星影像数据免费下载方式关于地理数据收集与处理的基本工具推荐(2)—10m精度的全球土地覆盖数据下载关于地理数据收集与处理…

勿忘2022,迎接2023

2022真的可以说是很不平凡的一年&#xff0c;很多想做的事情也因为一些原因没有做成。不过2022年已经过去&#xff0c;一年一度的总结还是要来写的。废话不多说&#xff0c;还是定关键词。2017年是“小确幸”和“在路上”&#xff0c;感谢师兄师姐的帮助&#xff0c;接触了很多…

write和fwrite

如果只是普通地以O_RDWR的flag去open一个文件朝里write&#xff08;不考虑创建、扩增&#xff09;&#xff0c;那默认内核会把文件的这个页面读进来缓存在内核里的&#xff0c;也即所谓的page cache。随后再发起新的write syscall写相同的页面时&#xff0c;只要写在page cache…

【博学谷学习记录超强总结,用心分享|产品经理基础总结和感悟13】

这里写目录标题第一章、概述第二章&#xff0c;内容服务产品分析框架&#xff1a;用户-平台-创作者内容服务平台优化思考第一章、概述 在分析文字类内容产品之前&#xff0c;我们先来思考一下内容产品的本质是什么&#xff1f;笔者认为&#xff0c;所有满足用户需求的信息服务…

aws beanstalk 使用docker平台部署beanstalk应用程序

参考资料 使用 Docker 平台分支 之前的文章分享过如何使用eb cli工具创建application和eb环境&#xff0c;本文介绍beanstalk支持的docker容器部署 关于beanstalk环境创建相关的资源和部署逻辑&#xff0c;参考之前的文章《aws beanstalk 使用eb cli配置和启动环境》 $ eb …

指南帮手——协议栈

通过 DNS 获取到 IP 后&#xff0c;就可以把 HTTP 的传输工作交给操作系统中的协议栈。协议栈的内部分为几个部分&#xff0c;分别承担不同的工作。上下关系是有一定的规则的&#xff0c;上面的部分会向下面的部分委托工作&#xff0c;下面的部分收到委托的工作并执行。应用程序…

PyTorch源码编译(windows)

1.打开pytorch源码仓库: https://github.com/pytorch/pytorch#from-source2.PyTorch用途与安装方法:3.Python与编译器版本要求 (Python3.7或者更高,编译器要求支持C17)4.如果要支持CUDA编程,要安装NVIDIA CUDA 11或者更高版本, 安装NVIDIA cuDNN v7或者更高版本注:CUDA不支持Ma…

使用 Flask 快速部署 PyTorch 模型

对于数据科学项目来说&#xff0c;我们一直都很关注模型的训练和表现&#xff0c;但是在实际工作中如何启动和运行我们的模型是模型上线的最后一步也是最重要的工作。 今天我将通过一个简单的案例&#xff1a;部署一个PyTorch图像分类模型&#xff0c;介绍这个最重要的步骤。 …

用一串Python代码爬取网站数据

如觉得博主文章写的不错或对你有所帮助的话&#xff0c;还望大家多多支持呀&#xff01;关注、点赞、收藏、评论。 目录一.编码问题二、文件编码三、基本方法四、登录五、断线重连六、正则匹配Excel操作转换网页特殊字符一.编码问题 因为涉及到中文&#xff0c;所以必然地涉及…

MV*系列架构模型

下文仅代表个人理解&#xff0c;可能会有偏差或错误&#xff0c;欢迎评论或私信讨论。 MVC 从软件架构模型角度 MVC 是比较“古老”的架构模型&#xff0c;后面的 MV* 都是基于它进行拓展。MVC 出现的意义是为了提高程序的可维护性与拓展性。在 View 层与 Model 层中添加了 C…