Java面试题每日10问(4)

news2025/1/16 8:01:23

Core Java - OOPs Concepts: Inheritance Interview Questions

1. Why use inheritance in java?

  • For Method Overriding (so runtime polymorphism can be achieved).
  • For Code Reusability.
    Terms used in Inheritance
    Class:
    –A class is a group of objects which have common properties.
    – It is a template or blueprint from which objects are created.
    Sub Class/Child Class:
    – Subclass is a class which inherits the other class.
    – It is also called a derived class, extended class, or child class.
    Super Class/Parent Class:
    – Superclass is the class from where a subclass inherits the features.
    – It is also called a base class or a parent class.
    Reusability:
    – reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class.
    – You can use the same fields and methods already defined in the previous class.
class Subclass-name extends Superclass-name  
{  
   //methods and fields  
}  

The extends keyword indicates that a new class that derives from an existing class. “extends” is to increase the functionality.

2.What are types of inheritance in java?

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.在这里插入图片描述
在这里插入图片描述

3.Why is multiple inheritance not supported in java?

  • To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

  • Consider a scenario where A, B, and C are three classes.
    The C class inherits A and B classes.
    If A and B classes have the same method and you call it from child class object
    there will be ambiguity to call the method of A or B class.

  • Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes.
    So whether you have same method or different, there will be compile time error.

4.What is aggregation?

  • Aggregation can be defined as the relationship between two classes where the aggregate class contains a reference to the class it owns.
  • Aggregation is best described as a has-a relationship.
  • For example, The aggregate class Employee having various fields such as age, name, and salary also contains an object of Address class having various fields such as Address-Line 1, City, State, and pin-code. In other words, we can say that Employee (class) has an object of Address class. Consider the following example.
public class Address {
    String city,state,country;

    public Address(String city, String state, String country) {
        this.city = city;
        this.state = state;
        this.country = country;
    }

}

public class Emp implements Cloneable{
    int id;
    String name;
    Address address;

    public Emp(int id, String name,Address address) {
        this.id = id;
        this.name = name;
        this.address=address;
    }

    void display(){
        System.out.println(id+" "+name);
        System.out.println(address.city+" "+address.state+" "+address.country);
    }

    public static void main(String[] args) {
        Address address1=new Address("gzb","UP","india");
        Address address2=new Address("gno","UP","india");

        Emp e=new Emp(111,"varun",address1);
        Emp e2=new Emp(112,"arun",address2);

        e.display();
        e2.display();

    }
}

111 varun
gzb UP india
112 arun
gno UP india

5.What is composition?

  • Holding the reference of a class within some other class is called composition.
  • an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.
  • composition is the particular case of aggregation which represents a stronger relationship between two objects.
  • example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

6. What is the difference between aggregation and composition?

  • Aggregation represents the weak relationship whereas composition represents the strong relationship.
  • For example, the bike has an indicator (aggregation), but the bike has an engine (composition).

7.Why does Java not support pointers?

  • the pointer is a variable that refers to the memory address.
  • they are not used in Java because it unsafe(unsecured) and complex to understand.

8.What is super in java?

  • The super keyword in Java is a reference variable which is used to refer immediate parent class object.

  • Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.

Usage of Java super Keyword

  1. super can be used to refer immediate parent class instance variable.
  2. super can be used to invoke immediate parent class method.
  3. super() can be used to invoke immediate parent class constructor.
    在这里插入图片描述

1) super is used to refer immediate parent class instance variable.

If we print color property, it will print the color of current class by default.
To access the parent property, we need to use super keyword.

public class Animal {
    String color="white";
}

public class Dog extends Animal{
    public static void main(String args[]){
        Dog d=new Dog();
        d.printColor();
    }
    String color="black";
    void printColor(){
        System.out.println(color);//prints color of Dog class
        System.out.println(super.color);//prints color of Animal class
    }
}
black
white

2)super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method.
It should be used if subclass contains the same method as parent class.
In other words, it is used if method is overridden.

public class Animal {
    void eat(){System.out.println("eating...");}
}
public class Dog extends Animal{
    void eat(){System.out.println("eating bread...");}
    void bark(){System.out.println("barking...");}
    void work(){
        super.eat();
        bark();
    }

    public static void main(String args[]){
        Dog d=new Dog();
        d.work();
    }
}
eating...
barking...
  • Animal and Dog both classes have eat() method, if we call eat() method from Dog class, it will call the eat() method of Dog class by default because priority is given to local.
  • To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.

  • default constructor is provided by compiler automatically if there is no constructor.
  • it also adds super() as the first statement.
public class Animal {
    Animal(){System.out.println("animal is created");}
}

public class Dog extends Animal{
    Dog(){
        super();//have no super()is ok
        //default constructor is provided by compiler automatically 
        System.out.println("dog is created");
    }

    public static void main(String args[]){
        Dog d=new Dog();
    }
}

animal is created
dog is created

Example:

public class Person {
    int id;
    String name;
    Person(int id,String name){
        this.id=id;
        this.name=name;
    }
}

public class Emp extends Person{
    float salary;
    Emp(int id,String name,float salary){
        super(id,name);//reusing parent constructor
        this.salary=salary;
    }
    void display(){System.out.println(id+" "+name+" "+salary);}

    public static void main(String[] args){
        Emp e1=new Emp(1,"ankit",45000f);
        e1.display();
    }
}

1 ankit 45000.0

9. What are the differences between this and super keyword?

There are the following differences between this and super keyword.

  • The super keyword always points to the parent class contexts whereas this keyword always points to the current class context.
  • The super keyword is primarily used for initializing the base class variables within the derived class constructor whereas this keyword primarily used to differentiate between local and instance variables when passed in the class constructor.
  • The super and this must be the first statement inside constructor otherwise the compiler will throw an error.

10. Can you use this() and super() both in a constructor?

No, because this() and super() must be the first statement in the class constructor.

public class Test{  
    Test()  
     {  
         super();   
         this();  
         System.out.println("Test class object is created");  
     }  
     public static void main(String []args){  
     Test t = new Test();  
     }  
}  
Test.java:5: error: call to this must be first statement in constructor

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

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

相关文章

皕杰报表点击导出按钮后网页变空白问题

有人反映使用皕杰报表导出时,点击导出按钮后网页变成了空白,然后就没有反应了。看tomcat控制台也没有错误信息,似乎遇到了一个很难缠的问题,没有错误信息却卡滞了,这个问题怎么解决呢? 还是要从tomcat的日志…

盘点微服务架构下的诸多身份验证方式

联合作者:罗泽轩,API7.ai 技术专家、Apache APISIX PMC 成员 联合作者:赵士瑞,API7.ai 技术工程师,Apache APISIX Committer 身份认证是授予用户访问系统并授予使用系统的必要权限的过程。而提供了这一功能的服务&…

指针详解——高级指针的解析及应用

目录 🐑指针的初步了解 🐂指针的深入认识 🦛1.指针数组 🐀指针数组的介绍 🐀指针数组的用法介绍 🐫2.数组指针 🦌数组指针的介绍以及使用 🦮3.函数指针 🐈函数指针的介绍…

Linux0基础入门:初识shell脚本编程

初识脚本编程到目前为止我们已经知道了 Linux 系统和命令行的基础知识,是时候开始编程了。本章讨论编写 shell 脚本的基础知识。在开始编写自己的 shell 脚本大作前,你必须了解这些基本概念。 使用多个命令到目前为止,你已经了解了如何使用 s…

Revit连接处理:阳台扶手和楼梯扶手,墙和梁

一、Revit中阳台扶手和楼梯扶手的连接处理 如图,有一些阳台扶手和楼梯扶手连接的地方,连接处需要进行处理。 1.在楼板合适的边缘处先画出楼梯 (1)单击“楼梯” (2)在楼梯类型属性对话框中修改楼梯属性 (3)绘制楼梯 为了定位方便、准确,首先要…

重塑底层逻辑,涅槃重生继续远航

背景介绍 从贫困县爬出来本硕均为211学校,在机械专业学习7年,有4年的时间热衷于编程学习。因此一路跨行到IT行业。 履历介绍 从毕业后一直在AI算法行业研究,呆过初创公司,目前在上市公司上班。尝尽IT的苦也吃过IT的甜。从毕业一…

【jQuery】常用API——jQuery效果

jQuery 给我们封装了很多动画效果,最为常见的如下:一、显示隐藏切换效果1. 显示语法规范 show([speed,[easing],[fn]]);显示参数:(1)参数都可以省略, 无动画直接显示。(2)speed&…

el-date-picker日期时间组件 报 placement 警告的解决方法

在使用el-date-picker组件时报这个警告,虽然不影响页面,但一打开页面跳出来一堆错误警告,实在受不了 解决办法:加上以下一行即可

无序字母对 -- 欧拉回路

洛谷:P1341 无序字母对题目描述前置知识欧拉路径定义判断是否为欧拉图思路code参考题目描述 题目描述 给定 n 个各不相同的无序字母对(区分大小写,无序即字母对中的两个字母可以位置颠倒)。请构造一个有 (n1) 个字母的字符串使得每…

同源、跨域的概念与实现

本文将结合周老师的讲义对同源与跨域这一前端经典问题进行系统的总结、整理。一起来坐牢,快! 1. 同源限制 1.1 历史背景 - 含义的转变 1995年,同源政策由 Netscape 公司引入浏览器。目前,所有浏览器都实行这个政策。 最初&…

爬虫代理Scrapy框架详细介绍4

Scrapy 框架 Scrapy实例 下载安装 pip install scrapy Hello World 创建工程 在 cmd 下切换到想创建 scrapy 项目的地方,然后使用命名 scrapy startproject tutorial 注:tutorial 为工程名 然后就会发现在当前位置会多出一个文件夹,名字是 tu…

C++——map|set介绍

目录 关联式容器 set set的构造 set的迭代器 set的容量 set修改操作 equal_range multiset map map的构造 map的迭代器 map的容量与元素访问 map测试 关联式容器 在初阶阶段,我们已经接触过STL中的部分容器,比如:vector、list、…

Linux内核权限提升漏洞

SSRF检测的一些思考 DNS平台没有立刻收到请求,是在之后的某个时间段收到了不同的请求信息,这至少表明了一点,此处存在有无回显的SSRF,虽然想要证明有更大的危害比较困难,但是至少说明了存在有SSRF的风险,所…

Maven 命令之将本地 Jar 包安装到 Maven 本地仓库

1、前言 Maven 是 Java 平台下的一款项目构建和依赖管理的自动化管理工具。 通过 Maven 远程仓库地址我们可以方便的管理 Jar 依赖包,但是在实际项目中有时候存在远程仓库中没有的 Jar 包,我们在项目中又必须要使用它,那就需要把本地 Jar 添…

HC-SR04超声波传感器使用

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录前言一、关于HC-SR04二、使用步骤1.确保驱动已经安装2.安装GPIO工具3.安装GPIO的Python支持4.Python3代码总结前言 最近在做一个项目,需要用到超声波传感…

誉辰智能拟科创板上市:欲募资4亿元,毛利率、研发费用率均下滑

近日,深圳市誉辰智能装备股份有限公司(下称“誉辰智能”)在上海证券交易所更新招股书(申报稿),披露时间为2023年1月7日,准备在科创板上市。据贝多财经了解,誉辰智能曾于2022年6月29日…

解决SpringBoot项目整合Sharding-JDBC后启动慢的问题

一、问题描述线上某一项目以jar包的方式发布,需要健康检查,若15次健康检查页面状态均为非200则健康检查失败,就会导致tomcat服务加载失败。前几天版本迭代,发布该项目时,因最后一次健康检查的时间比启动完成时早&#…

练习时长两年半的tcp三次握手

1、TCP是什么?TCP是面向连接的协议,它基于运输连接来传送TCP报文段,TCP运输连接的建立和释放,是每一次面向连接的通信中必不可少的过程。TCP运输连接有以下三个阶段:建立TCP连接,也就是通过三报文握手来建立…

Oracle打补丁

oralce打补丁 打补丁前提: 一、备份数据库 二、将oracle服务全部停掉 1、查看opatch的版本号 1.1、环境变量配置ORACLE_HOME 1.2、运行opatch version命令,查看opatch的版本号 备注:网上查看opatch的版本号对应的oracle是否匹配,…

【分治策略】查询中位数最接近点对

查询中位数给定线性序集中n个元素和一个整数k 【k(n1)/2】,要求找出这n个元素中第k小的元素,即找中位数。线性序列没有排序,没有重复值。已知快速排序划分时一个划分基准数的位置在确定后,在之后排序中是不会变的。利用此特性,以下…